Alex
Alex

Reputation: 68482

How to add hyphen to regex

I have encountered this pattern

(\w+)

and from http://gskinner.com/RegExr/ site I understand that \w = match alpha-numeric characters and underscores, and + = match previous token 1 or more times (not exactly sure what that means).

How can I add the hyphen character to the list?

I tried (\w\-+) but it doesn't work, I don't get any match ...

Upvotes: 2

Views: 3206

Answers (1)

Joey
Joey

Reputation: 354516

You need a character class, denoted by [...]. \w can then be used in the character class and more characters can be added:

[\w-]

Careful though, if you add more characters to match. The hyphen-minus needs to be first or last in a class to avoid interpreting it as a range (or escape it accordingly).

The + is a quantifier, so it goes after a token (where the whole character class is a single token [as is \w]):

([\w-]+)

Upvotes: 8

Related Questions