24

I'm having trouble creating a Regex to match URL slugs (basically, alphanumeric "words" separated by single dashes)

this-is-an-example 

I've come up with this Regex: /[a-z0-9\-]+$/ and while it restricts the string to only alphanumerical characters and dashes, it still produces some false positives like these:

-example example- this-----is---an--example - 

I'm quite bad with regular expressions, so any help would be appreciated.

2
  • What programming language? Commented Oct 8, 2013 at 19:17
  • @zzzzBov I'm using PHP (with the preg_match function). Commented Oct 8, 2013 at 19:19

2 Answers 2

75

You can use this:

/^ [a-z0-9]+ # One or more repetition of given characters (?: # A non-capture group. - # A hyphen [a-z0-9]+ # One or more repetition of given characters )* # Zero or more repetition of previous group $/ 

This will match:

  1. A sequence of alphanumeric characters at the beginning.
  2. Then it will match a hyphen, then a sequence of alphanumeric characters, 0 or more times.
Sign up to request clarification or add additional context in comments.

9 Comments

Great! This works almost as I want. Can you tweak it in order to match a single word too? (I forgot to mention that single words are considered valid slugs too).
@fedeetz: Just replace last + with * (0 or more matches)
@mathieug First, capturing group isn't wanted by the author, so what's the point of having it in your results? Secondly, The group is repeated, so with a repeated capturing group, only the last repetition would captured.
for the lazy: /^[a-z0-9]+(?:-[a-z0-9]+)*$/
@Yandiro /^[a-z0-9]+(?:[_-][a-z0-9]+)*$/
|
2

A more comprehensive regex that will match both ascii and non-ascii characters in slugs would be,

/^ # start of string [^\s!?\/.*#|] # exclude spaces/tabs/line feed.. as well as reserved characters !?/.*# + # match one or more times $/ # end of string 

for good measure we exclude the reserved URL characters.

so for example, the above will match

une-ecole_123-soleil une-école_123-soleil une-%C3%A9cole-123_soleil 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.