Quick Regex Question


Quick favor to ask, could someone help point me to a regex that filters out for any special characters except for “-” and “_”? Alphanumeric characters are allowed.

Thank you so much!

Hi Felix!

I don’t know of a shortcut that does exactly what you need, but here are some characters that might help, as well as a custom expression you could use.

Firstly, just to note: I’ve assumed you’re not counting whitespace (spaces between words, lines and tabs) as special characters for this answer. If you are, things get more complicated.

In terms of shortcuts, \w matches word characters (alphanumeric and “_”) and \s matches whitespace characters. Sadly neither matches “-”, but you could define a custom class using the not operator ^, which would look like this: [^\w\s-]

That should match anything that’s not alphanumeric, whitespace, “_” or “-”. Note that you have to ‘escape’ the hyphen with a backslash because otherwise it could be interpreted as a range indicator, as in a-z.

Alternatively, if you know exactly which special characters you’re looking for, you could write those out in a custom class, making sure to escape characters that could be interpreted as regex special characters, e.g. [!,+:?] for “!”, “,”, “+”, “:” and “?”.

This is the cheat sheet I use most often: Regex Cheat Sheet

And w3schools.com is good at explaining special regex characters, e.g. RegExp \w Metacharacter

Hope this helps!

This topic was automatically closed after 70 days. New replies are no longer allowed.