Search code examples
asp.net.netregexregular-language

regex where input has & char at end of string


I am using this regex:

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

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

My tests:

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

Why does the last test match?

It seems & char at the end string seprate them in two string. What is the solution that regex not match in http://example.com/abcd-p48343-fun&ab=1 ?

.*-p(.\d+)-fun$ also tested and not working.


Solution

  • This regex:

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

    Matches the first example only:

    VB.Net code:

    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()
    

    Console output:

    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