正则表达式输入有&字符串末尾的char

时间:2017-02-27 09:20:06

标签: asp.net .net regex regular-language

我正在使用这个正则表达式:

.*-p(.\d+)-fun\b含义:

.* => any char at the beginning, 
-p => static string ,
(.\d+) => number in first group,
-fun => static string ,
\b => end of string ,

我的测试:

http://example.com/abcd-p48343-fun             Matched 
http://example.com/abcd-p48343-funab           not matched
http://example.com/abcd-p48343-fun&ab=1        Matched 

为什么最后一次测试匹配?

似乎&最后的字符串将它们分成两个字符串。正则表达式在http://example.com/abcd-p48343-fun&ab=1中不匹配的解决方案是什么?

.*-p(.\d+)-fun$也经过测试而无法正常工作。

1 个答案:

答案 0 :(得分:1)

这个正则表达式:

.*-p(.\d+)-fun$

仅匹配第一个示例:

VB.Net代码:

Dim Tests As New List(Of String)
Dim Pattern As String
Dim Parser As Regex

Tests.Add("http://example.com/abcd-p48343-fun")
Tests.Add("http://example.com/abcd-p48343-funab")
Tests.Add("http://example.com/abcd-p48343-fun&ab=1")

Pattern = ".*-p(.\d+)-fun\b"
Parser = New Regex(Pattern)
Console.WriteLine("Using pattern: " & Pattern)
For Each Test As String In Tests
    Console.WriteLine(Test & " : " & Parser.IsMatch(Test).ToString)
Next
Console.WriteLine()

Pattern = ".*-p(.\d+)-fun$"
Parser = New Regex(Pattern)
Console.WriteLine("Using pattern: " & Pattern)
For Each Test As String In Tests
    Console.WriteLine(Test & " : " & Parser.IsMatch(Test).ToString)
Next
Console.WriteLine()

Console.ReadKey()

控制台输出:

Using pattern: .*-p(.\d+)-fun\b
http://example.com/abcd-p48343-fun : True
http://example.com/abcd-p48343-funab : False
http://example.com/abcd-p48343-fun&ab=1 : True

Using pattern: .*-p(.\d+)-fun$
http://example.com/abcd-p48343-fun : True
http://example.com/abcd-p48343-funab : False
http://example.com/abcd-p48343-fun&ab=1 : False