Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape forward slash in jscript regexp character class?

I have a regular expression testing for numbers(0-9) and/or forward slashes (/). It looks like this:

/^[0-9/]+$/i.test(value)

Now I believe this to be correct, but the eclipse javascript validator disagrees:

Syntax error on token "]", delete this token

I suppose this is because the separator/delimiter is / and eclipse 'thinks' the regex is finished (and therefore a ] would be unexpected).

We can satisfy eclipse by escaping the / like so:

/^[0-9\/]+$/i.test(value)

Note that both versions work for me.

My problem with this is:

  • As far as I know I do not need to escape the forward slash specifically in that range. It might be situation specific (as in, for javascript it is the used delimiter).
  • Although they both appear to be working, I'd rather use the 'correct' version because of behaviour in different environments, and, well.. because correct and all :)

Does anyone know what I'm supposed to do? Escape or not? I did not find any reputable site that told me to escape the / in a range, but the Eclipse-validator is probably not completely stupid...

like image 320
Nanne Avatar asked Feb 10 '12 11:02

Nanne


1 Answers

The standard clearly says you can put anything unescaped in a character class except \, ] and newline:

RegularExpressionClassChar ::
   RegularExpressionNonTerminator but not ] or \
   RegularExpressionBackslashSequence

RegularExpressionNonTerminator ::
    SourceCharacter but not LineTerminator

( http://es5.github.com/#x7.8.5 ). No need to escape /.

On the other side, I personally would escape everything when in doubt, just to make less smart parsers happy.

like image 57
georg Avatar answered Sep 19 '22 22:09

georg