L P
L P

Reputation: 1846

Regex to not match more than one trailing slash in string

Looking for a regex to not match more than 1 occurrence of a trailing slash

api/v1
/api/v1
/api/2v1/21/
/api/blah/v1/
/api/ether/v1//
/api/23v1///

Expected match

/api/v1
/api/2v1/21/
/api/blah/v1/

What I tried:

^\/([^?&#\s]*)(^[\/{2,}\s])$

Upvotes: 2

Views: 162

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

^(?:/[^/?&#\s]+)*/?$

See the regex demo.

Details

  • ^ - start of string
  • (?:/[^/?&#\s]+)* - zero or more repetitions of a / char followed with one or more chars other than /, ?, &, # and whitespace
  • /? - an optional /
  • $ - end of string.

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163217

In the pattern that you tried, the second part of the pattern can not match, it asserts the start of the string ^ and then matches a single character in the character class (^[\/{2,}\s])$ directly followed by asserting the end of the string.

^\/([^?&#\s]*)(^[\/{2,}\s])$

              ^^^^^^^^^^^^^^

But you have already asserted the start of the string here ^\/

You can repeat a pattern starting with / followed by repeating 1+ times the character class that you already have:

^(?:\/[^\/?&#\s]+)+\/?$

Explanation

  • ^ Start of string
  • (?:\/[^\/?&#\s]+)+ Repeat 1+ times / and 1+ char other than the listed ones
  • \/? Optional /
  • $ End of string

See a regex demo

Upvotes: 2

bobble bubble
bobble bubble

Reputation: 18490

By use of a negative lookahead:

^(?!.*//)/.*

See this demo at regex101

Upvotes: 3

Related Questions