在尝试回答问题Writing text into new line when a particular character is found时,我使用了Regexp::Grammars。它一直对我感兴趣,最后我有理由学习。我注意到作者的描述部分有一个LaTeX解析器(我是狂热的LaTeX用户,所以这让我很感兴趣)但是它有一个奇怪的构造在这里看到:
<rule: Option> [^][\$&%#_{}~^\s,]+
<rule: Literal> [^][\$&%#_{}~^\s]+
[^]
个字符类完成了什么?
答案 0 :(得分:21)
[^][…]
不是两个字符类,而是一个包含除]
,[
和…
以外的任何其他字符的字符类(请参阅Special Characters Inside a Bracketed Character Class):
但是,如果
]
是 first (或第二个,如果第一个字符是插入符号)括号中的字符类,则它不表示该类的结束(因为你不能有一个空类)并且被认为是可以匹配而没有转义的字符集的一部分。示例:
"+" =~ /[+?*]/ # Match, "+" in a character class is not special. "\cH" =~ /[\b]/ # Match, \b inside in a character class # is equivalent to a backspace. "]" =~ /[][]/ # Match, as the character class contains. # both [ and ]. "[]" =~ /[[]]/ # Match, the pattern contains a character class # containing just ], and the character class is # followed by a ].