2012-07-23 60 views
14

我将如何查找不在字符串内的关键字。正则表达式匹配不在引号中的关键字

例如,如果我有文本:

你好这段文字就是一个例子。

唧唧歪歪“这段文字是在字符串中”

“随机字符串”更多的文字唧唧歪歪“富”

我会喜欢能够匹配所有的话text那不在" "之内。在其他的我会想匹配:

enter image description here

注意到我不想被红色突出显示的文本匹配,因为它是一个字符串内


可能的解决方案:

我一直在努力,这是我到目前为止:

(?s)((?<q>")|text)(?(q).*?"|)

注意,正则表达式使用if语句为:(?(谓语)正确的选择|假替代)

所以正则表达式将读取:

查找“,或文本。如果您发现“则继续选择,直到找到”了(。*?“),如果您觉得有文字无能为力......

当我运行正则表达式我整个字符串匹配,虽然我是问这个我知道我可以删除所有的字符串,然后看看我需要什么

+0

你有没有试过一个在线正则表达式生成器,如:http://txt2re.com/index-csharp.php3 – Surfbutler 2012-07-23 20:53:13

+2

为什么你想匹配一个字符串,你知道什么是?你打算如何处理结果。意图对于其他人能够给出适当的答案很重要。 – Mithon 2012-07-23 20:55:48

+0

你不需要知道问题的意图,以便能够回答它。你也假设他知道弦是什么。他只举例说明他正在尝试做什么,这些不一定是他最终会用到的。他正在寻找一个具体的结果,这与我们如何使用这个结果无关。 – 2017-09-20 16:09:31

回答

20

这里有一个答案:

(?<=^([^"]|"[^"]*")*)text 

这意味着:

(?<=  # preceded by... 
^   # the start of the string, then 
([^"]  # either not a quote character 
|"[^"]*" # or a full string 
)*   # as many times as you want 
) 
text  # then the text 

您可以轻松地扩展这个到处理包含转义符的字符串。

在C#代码:

从评论的讨论
Regex.Match("bla bla bla \"this text is inside a string\"", 
      "(?<=^([^\"]|\"[^\"]*\")*)text", RegexOptions.ExplicitCapture); 

添加 - 扩展版(赛上每行的基础和处理逃逸)。使用RegexOptions.Multiline此:

(?<=^([^"\r\n]|"([^"\\\r\n]|\\.)*")*)text 

在C#中的字符串,这看起来像:

"(?<=^([^\"\r\n]|\"([^\"\\\\\r\n]|\\\\.)*\")*)text" 

既然你现在要使用**,而不是"这里是一个版本:

(?<=^([^*\r\n]|\*(?!\*)|\*\*([^*\\\r\n]|\\.|\*(?!\*))*\*\*)*)text 

说明:

(?<=  # preceded by 
^   # start of line 
(  # either 
[^*\r\n]| # not a star or line break 
\*(?!\*)| # or a single star (star not followed by another star) 
    \*\*  # or 2 stars, followed by... 
    ([^*\\\r\n] # either: not a star or a backslash or a linebreak 
    |\\.  # or an escaped char 
    |\*(?!\*) # or a single star 
    )*   # as many times as you want 
    \*\*  # ended with 2 stars 
)*  # as many times as you want 
) 
text  # then the text 

由于这个版本不包含"字符是清洁剂使用一个字符串:

@"(?<=^([^*\r\n]|\*(?!\*)|\*\*([^*\\\r\n]|\\.|\*(?!\*))*\*\*)*)text" 
+0

Porges感谢您的帮助!如果我在哪里有:''\ r \ n文本\ r \ n“bla bla ...'不会匹配......我猜这是因为'[^”]'会继续到下一行... – 2012-07-23 21:18:04

+1

@TonoNam:如果你希望它在每行的基础上匹配,那么将[[^“]'同时改为'[^”\ r \ n]',并将'RegexOptions.Multiline'添加到选项中。 – porges 2012-07-23 21:24:11

+0

谢谢!这是非常有帮助的 – 2012-07-23 21:26:12

5

这可能会非常棘手,但这里有一个潜在的方法,通过确保有偶数个引号在匹配文本和字符串末尾之间:

text(?=[^"]*(?:"[^"]*"[^"]*)*$) 

替换text与你想匹配的正则表达式。

Rubular:http://www.rubular.com/r/cut5SeWxyK

说明:

text   # match the literal characters 'text' 
(?=    # start lookahead 
    [^"]*   # match any number of non-quote characters 
    (?:   # start non-capturing group, repeated zero or more times 
     "[^"]*"  # one quoted portion of text 
     [^"]*   # any number of non-quote characters 
    )*    # end non-capturing group 
    $    # match end of the string 
)    # end lookahead 
+0

与上一次文字不符。但是知道这很有帮助! +1感谢您的帮助。 – 2012-07-23 21:02:42

1

我只想贪婪地匹配引号的文本的非捕获组内将它们过滤出来,然后用捕获组的不带引号的答案,就像这样:

".*(?:text).*"|(text) 

,你可能要细化一点的字边界等等。但是这应该让你你想去的地方,而且是一个明确的读取样本。

相关问题