tags:

views:

44

answers:

3

I'm sure this has been asked before, but I can't seem to find it (or know the proper wording to search for)

Basically I want a regex that matches all non-alphanumeric except hyphens. So basically match \W+ except exclude '-' I'm not sure how to exclude specific ones from a premade set.

+1  A: 
[^\w-]+

will do just that. Match any characters not in the \w set except hyphen.

Tim Pietzcker
+6  A: 

\W is a shorthand for [^\w]. So:

[^\w-]+

A bit of background:

  • […] defines a set
  • [^…] negates a set
  • Generally, every \v (smallcase) set is negated by a \V (uppercase) where V is any letter that defines a set.
  • for international characters, you may want to look into [[:alpha:]] and [[:alnum:]]
kch
Thanks, knew it'd be easy
Davy8
+1  A: 

You can use:

[^a-zA-Z0-9_-]

or

[^\w-]

to match a single non-hyphen, non-alphanumeric. To match one or more of then prefix with a +

codaddict
Underscore is missing (as well as lots of accented characters if his regex flavor considers characters like ä, ß or à to be part of `\w`)...
Tim Pietzcker
@Tim: Thanks for pointing.
codaddict