chinds
chinds

Reputation: 1829

regex to only allow a single occurrence of a char next to each other

So I have a current regx patten which matches how I want.

However I need to only allow for a single occurrence of say a / or - at any one time.

i.e.

allowed: /name/amp/test-123
not allowed: /name//amp/test-123
not allowed: /name/amp/test--123

This is my current regex:

([\w\/]+)\/amp(\/[\w-\/]+)

It matches those below correctly:

/name/name/amp/world-12345678/
/name/name/amp/world-12345678
/name/amp/snooker/12345678
/name/amp/snooker/12345678/
/name/amp/snooker/12345678

These strings should not be matched, but my regex matches them:

/name/amp/snooker//12345678
    #this shouldnt match because of the double `/`
/name/name/amp/world--12345678
    #this shouldnt match because of the double `-`

Upvotes: 0

Views: 312

Answers (2)

JazZ
JazZ

Reputation: 4579

Here is my two cents :

Example regex101

([\w\/]+)\/amp(\/\w+[-\/]\w+\/?)

(\/\w+[-\/]\w+\/?) Means :

- \/    -> Match literally "/"
- \w+   -> Match 1 or more character like [a-zA-Z0-9_]
- [-\/] -> (Here is the magic) Match literally "-" or "/" only once
- \w+   -> Match 1 or more character like [a-zA-Z0-9_]
- \/?   -> Match literally "/" zero or one time

Hope it helps.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You need to decompose the character class into a group based subpattern and make sure you allow a trailing / with \/?, and add anchors:

^([\w\/]+)\/amp(\/\w+(?:[-\/]\w+)*)\/?$
^                 ^^^^^^^^^^^^^^^^ ^^^^

See the regex demo

The ^ anchors the match at the string start, $ anchors it at the string end, and \w+(?:[-\/]\w+)* matches:

  • \w+ - 1 or more word chars
  • (?:[-\/]\w+)* - a non-capturing group matching zero or more sequences of the following subpatterns:
    • [-\/] - either - or /
    • \w+ - 1+ word chars.

Upvotes: 2

Related Questions