How to fix this regex pattern?

Viewed 64

I have this regex pattern ^(\/([a-z]+)?-?([a-z]+)?)+$ I am testing it in https://regex101.com/r/Se3e70/1/. The pattern it accepts are

  • /abc
  • /abc-def
  • /
  • /abc/abc
  • /abc/abc-def

but the problem is it also accepts

  1. /-
  2. /abc-

which I do not want.

How can I make sure to avoid these?

4 Answers

I believe this is what you want: some groups joined with -, but ending by the group without -

^(\/([a-z]+-?)*([a-z]+))+$

[
'/abc',
'/abc-def',
'/',
'/a',
'/abc/abc',
'/abc/abc-def',
'/-',
'/abc-',
].forEach(str => 
console.log(
/^(\/(([a-z]+)+(-[a-z]+)?)?)+$/.test(str)
))

^\/(([a-z]+)([-/][a-z]+)*)?$

I think this should work for you.

^\/

This part makes sure you have a string starting with a forward slash.

([a-z]+)

After the slash only letters from a to z are allowed.

([-/][a-z]+)*

This part makes sure that if there is a dash or slash it is followed by letters (which prevents e.g. /abc-). The star in the end ensures that /abc works but allows you to add multiple slash dash letter combinations.

(([a-z]+)([-/][a-z]+)*)?

The whole part is wrapped with a ? to make sure / also works. In theory you could add some none-capturing group markers (:?) to this if you do not need to actually know whats between the slashes.

[
'/abc',
'/abc-def',
'/',
'/abc/abc',
'/abc/abc-def',
'/-',
'/abc-','/a'
].forEach(str => 
console.log(
/^(\/([a-z\-]+[a-z]+)?([a-z]+)?)+$/.test(str)))
Related