How do I create a Perl regex that matches non-alphanumeric characters except spaces?

Joe Schmoe picture Joe Schmoe · Oct 20, 2010 · Viewed 16.1k times · Source

I have a Perl regex /\W/i which matches all non-alphanumeric characters, but it also matches spaces which I want to ignore. How do I get it to match non-alphanumeric characters except spaces?

Answer

steinar picture steinar · Oct 20, 2010

You could use

/[^\w\s]/

This matches all non-word characters (\w) and non-whitespace (\s).

EDIT:

/[^\w ]/

If you want only to ignore spaces (not all whitespace).

UPDATE:

Removed i as it's not needed (see several comments).