【发布时间】:2010-12-20 04:32:15
【问题描述】:
如何在 Visual Studio 搜索框中检索包含“strA”但不包含“strB”的文档的所有行?
【问题讨论】:
-
您是在命令行还是在某些代码中执行此操作?哪种操作系统或语言?
标签: visual-studio regex regex-negation
如何在 Visual Studio 搜索框中检索包含“strA”但不包含“strB”的文档的所有行?
【问题讨论】:
标签: visual-studio regex regex-negation
对于 Visual Studio 2012(和更新版本):
^(?!.*strB).*strA.*$
解释:
^ # 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
如果您还想删除回车符/换行符以及该行的其余部分,您可能需要在正则表达式的末尾添加 (?:\r\n)?。
【讨论】:
^(?!.*strB)(?!.*strC)(?!.*strD).*strA.*$.
对于 Visual Studio 2010(和以前的版本):
Visual Studio 搜索框有自己的奇怪版本的正则表达式语法。此表达式按要求工作:
^~(.*strB).*strA
^ 匹配一行的开头。 (通常对于文本编辑器,没有“多行”选项;^ 和 $ 始终在行边界处匹配。)
. 匹配除换行符以外的任何字符。 (通常情况下,似乎没有让点匹配换行符的“单行”或“全点”模式。)
~(...) 是“防止匹配”结构,相当于(据我所知)其他响应者使用的负前瞻 ((?!...))。
【讨论】:
^~(.*strB).*strA~(.*strB)。或~(strB).*strA.*~(strB).
您可以使用Negative lookarounds,但如果您不知道术语的预期位置(甚至顺序),则表达式会非常复杂。 你知道顺序或模式吗?
否则,我建议您使用另一个工具,该工具可以轻松地逐行循环(或列出 comp)文件并执行 inStr 或 Contains 或其他简单、更快的逻辑测试...
【讨论】:
我将假设搜索框实际上接受一般的正则表达式。使用负前瞻:
(?!^.*strB.*$)strA
您需要设置多行选项(^ 和 $ 在行的开头/结尾匹配)。如果您无法使用对话框选项进行设置,请尝试:
(?m)(?!^.*strB.*$)strA
这可能是该引擎中的默认模式。
【讨论】:
^ outside 放在前面,并在strA 前面添加另一个.*。但是没有必要将正则表达式的任何部分锚定到行的 end (即.*$ 可以去)。
这对我来说适用于 Visual Studio 2010:
^.+[^(strB)].+(strA).+[^(strB)].+$
【讨论】: