monti
monti

Reputation: 455

How to reject double slashes with a regular expression

I would like to build a regex which does:

I've build the following regex: ^[a-zA-Z0-9\/]+\/$.

The Regex Matches: a/b/c/ or 1/2/c/ I would like to not match a String like 1//a/

is this possible?

Upvotes: 1

Views: 835

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

The regex you may use is

^[a-zA-Z0-9]+(?:\/[a-zA-Z0-9]+)*\/$

See the regex demo.

Details

  • ^ - start of string
  • [a-zA-Z0-9]+ - 1 or more alphanumeric chars
  • (?:\/[a-zA-Z0-9]+)* - a non-capturing group that matches 0 or more repetitions of the following patterns:
    • \/ - a / char
    • [a-zA-Z0-9]+ - 1 or more alphanumeric chars
  • \/ - a / char
  • $ - end of string.

Note that / should not be escaped if / are not used as regex delimiters, or if regex delimiters are not used (in string literals, constructor notation, etc.).

Upvotes: 1

Related Questions