C# 在正则表达式中,(\W |$)是\b的可行替代方案吗?
我们有一个客户端应用程序,用户希望在其中搜索指定文本的“注释”字段。字段的格式为HTML或纯文本。我们最近做的一个更改是只支持“整词”匹配。使用C# 在正则表达式中,(\W |$)是\b的可行替代方案吗?,c#,regex,C#,Regex,我们有一个客户端应用程序,用户希望在其中搜索指定文本的“注释”字段。字段的格式为HTML或纯文本。我们最近做的一个更改是只支持“整词”匹配。使用\b,我们实现了这一点。模式: "\b(?:match)\b" <-- works 我将其更改为匹配\W,它可以工作,但它有一个缺点,即匹配的模式后面必须始终有另一个字符 "\b(?:7.0%)\W" <-- works, mostly 你是一个正确的轨道。当有字符时,表达式\b(?:7.0%)(\W |$)将与7.0%后面的字符匹配。相
\b
,我们实现了这一点。模式:
"\b(?:match)\b" <-- works
我将其更改为匹配\W
,它可以工作,但它有一个缺点,即匹配的模式后面必须始终有另一个字符
"\b(?:7.0%)\W" <-- works, mostly
你是一个正确的轨道。当有字符时,表达式
\b(?:7.0%)(\W |$)
将与7.0%
后面的字符匹配。相反,考虑使用一个否定的前瞻性<代码>(?!\w)< />代码,这样额外的字符不是匹配的一部分。
\b(?:7.0%)(?!\w)
如果字符串以
7.0%
结尾,它将匹配,如果字符串以7.0%结尾。
它将匹配7.0%
。它将匹配正则表达式选项是否为单线或多线。测试字符串是否会包含换行符,如果是,您是否希望$
匹配这些换行符或整个字符串的结尾?它可能包含换行符,但我不确定它是否真的与哪个匹配重要——我只想知道该字段包含搜索文本,作为一个整体。
"\b(?:7.0%)(\W|$)" <-- ??
Testing pattern '\b(?:7.0%)\b'
Input 'This string contains 7.0% embedded within it.'; result: False
Input 'In this string, 7.0%
is at the end of a line.'; result: False
Input '7.0% starts this string.'; result: False
Input 'This string ends with 7.0%'; result: False
Testing pattern '\b(?:7.0%)\W'
Input 'This string contains 7.0% embedded within it.'; result: True
Input 'In this string, 7.0%
is at the end of a line.'; result: True
Input '7.0% starts this string.'; result: True
Input 'This string ends with 7.0%'; result: False
Testing pattern '\b(?:7.0%)(\W|$)'
Input 'This string contains 7.0% embedded within it.'; result: True
Input 'In this string, 7.0%
is at the end of a line.'; result: True
Input '7.0% starts this string.'; result: True
Input 'This string ends with 7.0%'; result: True
Testing pattern '\b(?:7.0%)(?!\w)'
Input 'This string contains 7.0% embedded within it.'; result: True
Input 'In this string, 7.0%
is at the end of a line.'; result: True
Input '7.0% starts this string.'; result: True
Input 'This string ends with 7.0%'; result: True
\b(?:7.0%)(?!\w)