正则表达式 for "111 -> c:my sourcefile1.cpp (no code)" (C#)



我需要在c#中解析一个包含以下内容的字符串:

111 -> c:my sourcefile1.cpp (no code)
112 -> c:my sourcefile1.cpp
113 -> c:my sourcefile2.cpp
114 -> c:my sourcefile3.cpp
115 -> c:my sourcefile2.cpp (no code)

我需要得到第一个数字和文件名,但只有记录与代码(所以不应该有(没有代码)在结束。目前我已经结束了这个rexex

new Regex(@"^(d+) -> ([^rn]*)", RegexOptions.Multiline | RegexOptions.IgnoreCase)

它真的很简单,但是它给了我一些我不想看到的线条。我所有写^(d+) -> ([^rn]*)(?! (no code))的尝试都失败了。实际上,这可能是一个更一般的例子。如:如何在"aaa BBB ccc"形式的字符串中匹配BBB,其中BBB可以是任何字符集,aaa和ccc是已知的令牌,由与BBB相同的字符集组成?

为什么不能直接使用:

^(d+) -> ([w:\s.]+)$

应用多行,它将不允许(no code),因为它不包含在最后一组中(最后一组的类中不允许有括号)

如果你确实需要在文件名中使用圆括号,你可以这样使用:

^(d+) -> (.+?)(?<! (no code))$

使用负向后看(这样你就可以确保它不会出现在行尾之前)。

我用c#测试了它,它为我工作。

new Regex(@"^(d+)s->s(.+.w+)(?!.*(no code))$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

这和你的尝试没什么不同,

^(d+) -> ([^rn]*)(?! (no code))

但我认为你的中间部分([^rn]*)匹配太多,所以负向前看将不再匹配。

更新:

我测试了@Brad Christie的解决方案

new Regex(@"^(d+) -> (.+?)(?<! (no code))$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

,它也与。net/c#在我的环境中工作,所以+1

相关内容

最新更新