我如何能够查找不在字符串中的kewords.
例如,如果我有文字:
你好,这个文字就是一个例子.
bla bla bla"这个文字在一个字符串里面"
"随机字符串"更多文字bla bla bla"foo"
我希望能够匹配所有text不在里面的单词" ".在其他我想匹配:

注意我不想匹配红色突出显示的文本,因为它在字符串中
可能的方法:
我一直在努力,这是我到目前为止:
(?s)((?<q>")|text)(?(q).*?"|)
请注意,正则表达式使用if语句:(?(谓词)true替换| false替代)
所以正则表达式会读:
找到"或文字.如果你找到"然后继续选择,直到你找到"再次(.*?"),如果你找到文字,然后什么都不做......
当我运行该正则表达式时,我匹配整个字符串.我问这个问题是为了学习.我知道我可以删除所有字符串然后寻找我需要的东西.
por*_*ges 21
这是一个答案:
(?<=^([^"]|"[^"]*")*)text
Run Code Online (Sandbox Code Playgroud)
这意味着:
(?<= # 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
Run Code Online (Sandbox Code Playgroud)
您可以轻松扩展它以处理包含转义的字符串.
在C#代码中:
Regex.Match("bla bla bla \"this text is inside a string\"",
"(?<=^([^\"]|\"[^\"]*\")*)text", RegexOptions.ExplicitCapture);
Run Code Online (Sandbox Code Playgroud)
从评论讨论中添加 - 扩展版本(基于每行匹配并处理转义).使用RegexOptions.Multiline此:
(?<=^([^"\r\n]|"([^"\\\r\n]|\\.)*")*)text
Run Code Online (Sandbox Code Playgroud)
在C#字符串中,这看起来像:
"(?<=^([^\"\r\n]|\"([^\"\\\\\r\n]|\\\\.)*\")*)text"
Run Code Online (Sandbox Code Playgroud)
既然您现在想要使用**而不是"这里是一个版本:
(?<=^([^*\r\n]|\*(?!\*)|\*\*([^*\\\r\n]|\\.|\*(?!\*))*\*\*)*)text
Run Code Online (Sandbox Code Playgroud)
说明:
(?<= # 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
Run Code Online (Sandbox Code Playgroud)
由于此版本不包含"字符,因此使用文字字符串更简洁:
@"(?<=^([^*\r\n]|\*(?!\*)|\*\*([^*\\\r\n]|\\.|\*(?!\*))*\*\*)*)text"
Run Code Online (Sandbox Code Playgroud)
这可能会变得非常棘手,但是这里有一种可能的方法可以确保匹配的文本和字符串的结尾之间存在偶数个引号:
text(?=[^"]*(?:"[^"]*"[^"]*)*$)
Run Code Online (Sandbox Code Playgroud)
替换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
Run Code Online (Sandbox Code Playgroud)