2

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 ...

1
  • Note that U+002D is really HYPHEN-MINUS, and that U+2010 is the real HYPHEN character. Commented Feb 24, 2012 at 19:09

1 Answer 1

8

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-]+)
Sign up to request clarification or add additional context in comments.

2 Comments

Capturing groups can be pretty useful.
If (\w+) is the complete regex, then you don't need a group, as the match alone suffices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.