简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM