什么时候需要转义正则表达式字符集中的字符(在[]内)? [英] When do I need to escape characters within a regex character set (within [])?
问题描述
我在括号中逃脱的规则与我在括号外所做的规则不同吗?
Are the rules for what I escape in a bracket different for what I do outside of brackets?
例如我应该在括号内转义?
吗?是/blah [^?]/
还是/blah [^ \?]/
For example should I escape a ?
inside a bracket? Is it /blah[^?]/
or /blah[^\?]/
括号的规则是否有所不同,还是我应该将两者都转义?
Are the rules for brackets different than not, or should I be escaping both the same?
推荐答案
唯一需要用方括号括起来的东西是一个右括号,如果不是首字母或结尾,则为负号;如果是首字母,则为一顶帽子., 据我所知.还有反斜杠本身.
The only thing that needs to be escaped in brackets is a closing bracket, and a minus if it is not initial or final, and a hat if it is initial, AFAIK. And the backslash itself, obviously.
原因是,这些是方括号内唯一具有特殊意义的字符.右方括号括在方括号中,中间的减号表示范围,首字母否定方括号.其他所有内容都应按字面解释.反斜杠是转义符,因此您需要一个双反斜杠来匹配文字反斜杠.
The reason is, these are the only characters with a special significance inside the brackets. A closing bracket ends the brackets, a mid-string minus indicates a range, and an initial hat negates the bracket class. Everything else should be literally interpreted. The backslash is the escape character, so you need a double backslash to match a literal backslash.
这篇关于什么时候需要转义正则表达式字符集中的字符(在[]内)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!