我没有看到这个正则表达式问题的完全重复...
在Visual Studio 2012中,我需要找到所有带有'using'指令的文件,这些指令与特定的名称空间相匹配。
示例:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
我想找到所有'System'(substring A)命名空间引用,除了包含'Collections'(子串B)的那些。
期望的结果:
using System;
using System.Data;
using System.Diagnostics;
似乎是使用正则表达式的好地方。
答案 0 :(得分:0)
这是似乎有效的最低正则表达式:
^.*System(?!\.Collections).*$
将其分解为部分:
^ # from the beginning of the string
.* # match all leading ('using ' in my case)
System # match 'System'
(?!\.Collections) # don't match strings that contain '.Collections'
.*$ #match all (.*) to the end of the line ($)
此变体:
^.*[ ]System(?!\.Collections).*$
将消除
using my.System.Data;
using mySystem.Diagnostics;
警告:大约20年前,我上次认真对待正则表达式,所以我再次成为新手......希望我得到正确的解释。
答案 1 :(得分:0)
您需要了解
(?!...)
。零宽度负向前瞻。(?<!...)
。零宽度负面看后面正则表达式
Regex rxFooNotBar = new Regex( @"(?<!bar)Foo(?!Bar)" ) ;
将匹配包含“Foo”但不包含“Bar”的字符串。
对于您的特定情况 - 查找引用using
没有'Collections'作为子命名空间的System
命名空间的Regex rxUsingStatements = new Regex( @"^\s*using\s+System\.(?!Collections)[^; \t]*\s*;" ) ;
语句,这应该可以解决问题:
{{1}}
应该做你。