2

enter image description here

What is the easiest way to rectify my failing inspection? There is no option in intellij (that I can find) to allow character classes inside a character range.

Sepster
  • 4,800
  • 20
  • 38
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • 2
    why do you have `\w` inside `[]`? – Evan Davis Mar 10 '13 at 14:54
  • @Mathletics becuase I know nothing about regex's and just copied from another SO answer. – NimChimpsky Mar 10 '13 at 18:36
  • There's nothing wrong with having `\w` in an `[]`. – MikeM Mar 10 '13 at 22:05
  • @NimChimpsky as per my answer below, because the un-escaped hyphen has special meaning inside a character class (it creates a "range" of included characters, eg `a-z` or `0-9`) I'd expect this regex is not correct as it sits (I'm assuming the intent of the hyphen in your character class is to allow a _literal_ hyphen in the target string at that point in the email address?). As such, would you mind providing a reference the specific SO answer so that it can be corrected if/as appropriate? – Sepster Mar 11 '13 at 06:12

1 Answers1

9

If you want to allow a literal hyphen - in a character class, you need to put it immediately after the opening [ (Refer "Character Classes" section at http://www.regular-expressions.info/reference.html) or immediately prior to the closing ] (I've found works in some languages at least), else it's deemed to signify a range.

And note also this comment by @IanMackinnon on this SO question (although I couldn't find an authoritative source for this after a very brief search): "explicitly escaping hyphens in character classes is another JSLint recommendation." - this was written in the context of literal hyphens. Regardless of if jsLint needs this or not to pass inspection, it's probably good practice to do this in order to future-proof the literal hyphen in case a future developer accidentally turns the class into a range by putting something between the (un-escaped) hyphen and the opening (or closing) bracket.

I therefore think the section of your regex that currently reads as [\w-+\s] should be re-written as [\-\w+\s]).

And the subsequent [\w-+] as [\-\w+], etc...

Community
  • 1
  • 1
Sepster
  • 4,800
  • 20
  • 38
  • The first bit is wrong - he is passing a regex literal to the RegExp contructor (unnecessarily), and `\w` would only need to be `\\w` if it was a string. He either needs to escape the hyphen `\-` or put it at the start or end of the class as you suggest. – MikeM Mar 10 '13 at 13:42
  • @MikeM Indeed - Thanks for highlighting my error, have updated my answer to reflect. – Sepster Mar 10 '13 at 13:48