Skip to main content
 首页 » 编程设计

c#之C# 中的正则表达式,负向后视中的表达式

2024年01月26日27kenshinobiy

我正在尝试编写一个表达式来匹配前面有奇数个问号的单引号。

我找到了一个否定的后视表达式来匹配一个问号

pattern (?<!\?)' 
 
aaa?'aaa   match 
aaa'aaaa   not match 
aaa??'aaa  match --wrong 

但我需要的是检测奇数个问号,而不是一个。
我试着把它写成 (?<!\?(??))'但它没有用。

我想要的结果是

aaa?'aaaa  match 
aaa??'aaaa  not match 
aaa???'aaaa  match 
aaa????'aaaa  not match 
aaa?????'aaaa  match 

请您参考如下方法:

您要查找的正则表达式是 (?<=(^|[^?])(\?\?)*\?)' .

让我们打破回顾(我把它改成正面的):

(^|[^?]) not a question mark (possibly also start of string, i.e. nothing) 
(\?\?)*  any number of question mark pairs 
\?       a single question mark 

因此,为了使报价匹配,必须以相反的顺序在其前面加上这些标记。应该清楚的是,对于某些 N >= 0,这会强制前面问号的数量恰好为 2N + 1。