Search code examples
regexregex-negationregex-groupregex-greedy

Regex - Match the characters but not the forward slash


I am actually looking for the regex. Basically I want to match the below URL

/test/*/contact/*

My inputs are something like this

/test/1234/contact/abcd  ----   This is correct
/test/abcd/1234/contact/abcd --- This should show not match

I tried the regex as

\/test\/\S+\/contact\/\S+

By using the above exp it is showing both are correct. can someone help me how to exclude the forward slash?


Solution

  • The \S pattern matches /. You should rely on [^\/] negated character class and use anchors:

    ^\/test\/[^\/]+\/contact\/[^\/]+$
    

    See the regex demo

    Details

    • ^ - start of string
    • \/test\/ - /test/
    • [^\/]+ - 1+ chars other than /
    • \/contact\/ - /contact/
    • [^\/]+ - 1+ chars other than /
    • $ - end of string.