Raghvender Kataria
Raghvender Kataria

Reputation: 1485

Need help in writing Regular expression

Can someone help me in writing regular expression to match such kind of string

Rules are:

  1. It should start with nl
  2. It can or cannot have one parameter in between nl and contact (like /abc/) but not ( /abc/def/)
  3. It can have anything after contact

Examples:

nl/abc/contact --> allowed

nl/contact --> allowed

nl/abc/def/contact --> not allowed

nl/abc/contact/mno --> allowed

nl/abc/contactmno/ ---> not allowed

I tried writing one ("^nl(.?)/contact(.)$"), but it has a problem that it allows any number of slashes between nl and contact wheras I just want at max one slash in between

Upvotes: 1

Views: 33

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522824

I would use:

^nl(?:/[^/]+)?/contact(?:/[^/]+)*$

Demo

This pattern says to match:

^            from the start of the path
nl           starts with "nl"
(?:/[^/]+)?  any zero or one path parameter following
/contact     /contact
(?:/[^/]+)*  followed by zero or more other path parameters
$            end of the input

Upvotes: 1

Related Questions