【发布时间】:2012-02-16 12:01:20
【问题描述】:
我希望使用 .NET 正则表达式查找不在双引号内的每个单词。以下是一些示例文本:
Hello world I want to get all of these words as a match "but not these ones...
because they're inside a string. And maybe I'll \"escape\" the quotes too." Also,
these words should match. Now we're outside of the string. And I can't escape
quotes; \"this still shouldn't be matched."
所以我想匹配:
Hello, world, I, want, to, get, all, of, these, words, as, a, match, Also,
these, words, should, match, Now, we, re, outside, of, the, string, And, I,
can, t, escape, quotes
这可能使用 .NET 正则表达式外部堆栈和断言吗?我已经走到这一步了:
(?<=(?(rstack)|(?!))(?<-rstack>").*?(?<rstack>").*?)\w+... same thing for fstack
'当然,它不起作用。
【问题讨论】:
-
如果没有平衡分组结构,似乎有一个简单的解决方案来获得所需的输出(删除
\".*?(?:$|(?<!\\)\")的匹配项,然后在结果字符串中找到\w+的匹配项)。由于输入中没有平衡(任何地方的引号看起来都是合法的,没有嵌套,并且打开/关闭分隔符相同),在什么情况下断言会失败? -
@drf:我希望永远不会(如果它们不平衡,请忽略它们)但几乎任何事情都可以。