2017-02-27 14 views
0

我使用這個正則表達式的結束字符:正則表達式,其中輸入具有與在串

.*-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 

爲什麼最後的測試匹配?

看起來好像是& char在結尾字符串將它們分隔爲兩個字符串。正則表達式在http://example.com/abcd-p48343-fun&ab=1中不匹配的解決方案是什麼?

.*-p(.\d+)-fun$也測試過,不能正常工作。

+0

它不匹配:https://regex101.com/r/H9mzsp/1 –

+0

@PawełŁukasik - OP是使用.net風格的正則表達式不是PCRE –

+0

@PawełŁukasik看看這個http://regexr.com/3fd4o – Moslem7026

回答

0

此正則表達式:

.*-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