1
"foo = '@test.bar';\nfooa = @test.darn;".match(/@([a-z][a-z\.-_]*)/igm)

Why does this match

["@test.bar", "@test.darn;"]

rather than just

["@test.bar", "@test.darn"]

?

5
  • 4
    I guess the range from . to _ includes ; but not ' Commented Jan 21, 2013 at 0:41
  • Did you want to include the "-" character or you really wanted to specify a range ? Commented Jan 21, 2013 at 0:45
  • 1
    @elclanrs \w also includes \d Commented Jan 21, 2013 at 0:47
  • Funnily enough, the \ is actually included in that range as well, so the \ in the OP's question is doubly redundant. Commented Jan 21, 2013 at 0:47
  • @inhan: Oh, yeah you're right...I think OP want's - as well, so it wasn't a range anyway. Commented Jan 21, 2013 at 0:49

1 Answer 1

5

In character classes, some letters have special meanings. The dot for example has none and does not need to be escaped. The minus in contrast defines a range of characters, and if you mean literally minus you need to escape it or put it in the end/beginning of the character class. Your range from . to _ actually includes ./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_. You may want to use [a-z.\-_] or [a-z._-] instead.

Sign up to request clarification or add additional context in comments.

6 Comments

oh. I always thought dot had to be escaped while minus hadn't, nice catch.
@Nico: Typically no character that has special meaning outside [] has to be escaped inside. The - needs to be escaped because it has special meaning inside [].
@elclanrs Not true. You need to escape the closing square bracket as well - not to mention the back slash nd the caret of course.
@elclanrs ^ has to be escaped inside a character class as well.
@inhan & @JanDvorak: Well, yeah.. ^ has special meaning inside [] so it has to be escaped, and ] well I think that one seems pretty obvious...
|

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.