Regex: Use a string structure, excluding capital letters

Viewed 43

I would like to match a string with the following structure string1-string2-string3 where each string can include numerics but no capital letters.

a concrete example would be "hello-world-today"

I have a regex expression, but I am sure it's not optimal since I repeat the same pattern three times.

'([a-z0-9]([-a-z0-9]*[a-z0-9])?)-(([a-z0-9]([-a-z0-9]*[a-z0-9])?))-(([a-z0-9]([-a-z0-9]*[a-z0-9])?))'

1 Answers

This should be an effective way:

^(?:[a-z\d]+-){2}([a-z\d]+)$

It matches two groups of lowercase letters and numbers followed by a dash and then another group of the same characters without the dash at the end.

Related