Written by Sean Behan on Thu Aug 22nd 2013

This regular expression matches non alphanumeric characters in a string.

r = /[^a-z0-9]{1,}/i

You can use it to create URL friendly slugs.

 slug = "hello world!".gsub(/[^a-z0-9]{1,}/i, '-').downcase # => hello-world

In combination with String#gsub it will replace the non alphanumeric characters with a dash "-" ... or anything you want.

The important bit here is the {1,} in the regular expression. This prevents URLs from having multiple dashes when multiple non alpha numeric characters are found next to each other.

For instance,

"hello, world" should be "hello-world" and not "hello--world" (two dashes in the latter).

Tagged with..
#Regular Expressions #Ruby #Strings

Just finishing up brewing up some fresh ground comments...