Is using / inside a character class in a regular expression always safe?

When using a regex literal in JavaScript, it is / -delimited, for example. /^[az]$/ .

When the slash in this regular expression is included, i.e. /^[az/]$/ , everything works fine - both the IDE syntax syntax and the Firefox and Chrome JS parsers accept it.

Is it a standardized behavior that / does not need to be escaped within the character class or just for a developer-compatible implementation, and therefore does not work in all browsers?

+7
javascript regex
source share
1 answer

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

RegularExpressionClass ::
[ RegularExpressionClassChars ]

RegularExpressionClassChars ::
[empty]
RegularExpressionClassChars RegularExpressionClassChar

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

RegularExpressionNonTerminator ::
SourceCharacter , but not LineTerminator

Unlike a regular NormalExpressionChar, it is defined as:

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

So, in character classes you are free to use / without the need for escaping.

+11
source share

All Articles