5

/}/是 JS 中的有效正则表达式:

alert('}}}'.replace(/}/g, "!"))

但是,ECMA 标准似乎不允许这样做:

PatternCharacter ::SourceCharacter but not any of:
      ^ $ \ . * + ? ( ) [ ] { } |

为什么上述工作?是否普遍支持此功能?它在任何地方都有记录吗?

4

2 回答 2

3

小修正:这些是RegExpes,和纯正则表达式不同。

为什么上述工作?

因为您使用的 JS 实现并不严格符合 ES5 标准,该标准规定它应该引发SyntaxError. 正如 Bergi 评论的那样,这在$15.10.4.1中有所描述。

是否普遍支持此功能?

不,如果它不在标准中,则永远不应被视为普遍支持。

它在任何地方都有记录吗?

可能不是,它只是未定义行为的产物。查看您测试过的任何 JS 引擎的文档。

于 2012-10-18T10:56:18.947 回答
1

http://www.regular-expressions.info/characters.html :

Most regular expression flavors treat the brace { as a literal character, unless it is part of a repetition operator like {1,3}. So you generally do not need to escape it with a backslash, though you can do so if you want. An exception to this rule is the java.util.regex package: it requires all literal braces to be escaped.

Seems that javascript is not an exception.

于 2012-10-18T11:03:42.623 回答