了解否定字符类 [英] Understanding the negated character class
问题描述
正则表达式:
/''+[^f]/g
应用于字符串时:
don't '''theater''' but not'''d and not do'''f
还匹配 do'''f
中的三个撇号.为什么 [^f]
不排除它?
also matches the three apostrophes in do'''f
. Why is the [^f]
not excluding it?
小提琴是这里.
PS:我想找到连续的两个或多个撇号后跟不是 f.
PS: I want to find consecutive two or more apostrophes followed by not an f.
推荐答案
+
使正则表达式引擎在 2 个或多个 之后找到
s.您可以在否定前瞻中使用 f
后回溯''
替代项来防止(以免使用 f
和 '
以外的字符,当您使用 [^f]
,该字符成为匹配的一部分,因为否定字符类是一个消耗模式,而前瞻是零宽度断言).
The +
makes the regex engine backtrack once a f
is found after 2 or more '
s. You may prevent with a '
alternative in a negative lookahead (so as not to consume the character other than f
and '
, when you use [^f]
, the character becomes part of the match since a negated character class is a consuming pattern and lookaheads are zero-width assertions).
''+(?!['f])
查看正则表达式演示.这里,(?!['f])
将阻止匹配,如果 2 个或多个 '
符号后跟 f
或 '代码>.此外,您可以使用限制量词
{2,}
(出现 2 次或更多)来编写它:'{2,}(?!['f])
.
See the regex demo. Here, (?!['f])
will prevent a match if 2 or more '
symbols are followed with f
or '
. Also, you may write it with a limiting quantifier {2,}
(2 or more occurrences): '{2,}(?!['f])
.
如果您的正则表达式引擎支持防止回溯到量化模式的占有量词,请使用一个:
If your regex engine supports possessive quantifiers that prevent backtracking into the quantified patterns, use one:
''++(?!f)
^^
参见另一个演示(另一种编写方式是'{2,}+(?!f)
).
See another demo (another way of writing it is '{2,}+(?!f)
).
如果您正在使用不支持所有格量词的 .NET 正则表达式库,您可以使用原子组代替(其工作方式与所有格量词相同,但适用于整个组):
If you are using a .NET regex library that does not support possessive quantifiers, you may use the atomic group instead (that works the same way as possessive quantifier, but for the entire group):
(?>'{2,})(?!f)
这篇关于了解否定字符类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!