Home > Software design >  Regex match a string followed by 1 forward slash
Regex match a string followed by 1 forward slash

Time:09-12

I need to match a string with alphanumeric, underscores and dashes only followed by one or zero forward slash only.

These are valid:

aBc
ab-9/
a_C-c/
3-b-c

These are invalid:

aBc/xyz
1bc/x7z/
hello//
a-b_/89u/13P

I am trying this:

([a-zA-Z0-9-_]{1,})(?=\\?)

But it is not working. It is still matching, for example, this: a-b_/89u/

Please help

CodePudding user response:

Using a pattern like (?=\\?) the positive lookahead will always be true as the question mark makes it optional, so it will match one of more occurrences of [a-zA-Z0-9-_]

In this case you could use a capture group for the part that you want, and optionally match / at the end of the string.


If you don't want to match double hyphens and an optional / at the end:

^(\w (?:-\w )*)\/?$

Regex demo

With a lookahead:

^\w (?:-\w )*(?=\/?$)

Regex demo

Or If you want to allow mixing chars, you can write it as:

^[\w -] (?=\/?$)

Regex demo

  • Related