Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using a / within a character class in a regex literal always safe?

When using a regex literal in JavaScript it's /-delimited, e.g. /^[a-z]$/.

When including a slash in that regex, i.e. /^[a-z/]$/, everything seems to work fine - both my IDE's syntax highlighter and the JS parsers of Firefox and Chrome accept it.

Is it standardized behavior that / does not need to be escaped within a character class or just a developer-friendly implementation and thus not work in all browsers?

like image 924
ThiefMaster Avatar asked Jul 02 '13 08:07

ThiefMaster


1 Answers

Yes, this is defined by the specification (p. 25):

RegularExpressionClass ::
    [ RegularExpressionClassChars ]

RegularExpressionClassChars ::
    [empty]
    RegularExpressionClassChars RegularExpressionClassChar

RegularExpressionClassChar ::
    RegularExpressionNonTerminator but not one of ] or \     RegularExpressionBackslashSequence

RegularExpressionNonTerminator ::
    SourceCharacter but not LineTerminator

In contrast, the normal RegularExpressionChar is defined as:

RegularExpressionChar ::
    RegularExpressionNonTerminator but not one of \ or / or [
    RegularExpressionBackslashSequence
    RegularExpressionClass

So within character classes you can use / freely without the need for escaping.

like image 171
Joey Avatar answered Nov 06 '22 18:11

Joey