Regex:如何在Visual Studio中检索包含strA但不包含strB的所有行

Ric*_*cky 19 regex visual-studio regex-negation

如何在Visual Studio搜索框中检索包含"strA"但不包含"strB"的文档的所有行?

Tim*_*ker 35

对于Visual Studio 2012(以及更新版本):

^(?!.*strB).*strA.*$
Run Code Online (Sandbox Code Playgroud)

说明:

^           # Anchor the search at the start of the line
(?!.*strB)  # Make sure that strB isn't on the current line
.*strA.*    # Match the entire line if it contains strA
$           # Anchor the search to the end of the line
Run Code Online (Sandbox Code Playgroud)

(?:\r\n)?如果您还想删除回车符/换行符以及行的其余部分,则可能需要在正则表达式的末尾添加.

  • 这很有效.我必须扩展以支持多个字符串以进行排除,例如`^(?!.*strB)(?!.*strC)(?!.*strD).*strA.*$`. (6认同)

Ala*_*ore 18

对于Visual Studio 2010(和以前的版本):

Visual Studio搜索框有自己的,奇异的正则表达式语法版本.此表达式按要求工作:

^~(.*strB).*strA
Run Code Online (Sandbox Code Playgroud)

^匹配一行的开头.(通常对于文本编辑器,没有"多行"选项; ^并且$始终在行边界处匹配.)

.匹配除换行符之外的任何字符.(不常见的是,似乎没有"单线"或"全点"模式,让点匹配换行符.)

~(...)是"防止匹配"构造,等同于(据我所知)(?!...)其他响应者使用的负向前瞻().

  • 仅供参考,从Visual Studio 2012开始,dotNet正则表达式引擎现在用于搜索,因此奇怪的语法现在应该消失了.很好的答案,但只是要知道你正在使用哪个版本的VS. (5认同)

ann*_*ata 1

您可以使用否定环视,但如果您不知道术语的预期位置(甚至顺序),则表达式会非常复杂。你知道顺序或模式吗?

否则,我建议您使用另一个工具,它可以轻松地逐行循环(或列出 comp)文件并执行 inStr 或 Contains 或其他简单、更快的逻辑测试...