这里有一个答案:
(?<=^([^"]|"[^"]*")*)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"
你有没有试过一个在线正则表达式生成器,如:http://txt2re.com/index-csharp.php3 – Surfbutler 2012-07-23 20:53:13
为什么你想匹配一个字符串,你知道什么是?你打算如何处理结果。意图对于其他人能够给出适当的答案很重要。 – Mithon 2012-07-23 20:55:48
你不需要知道问题的意图,以便能够回答它。你也假设他知道弦是什么。他只举例说明他正在尝试做什么,这些不一定是他最终会用到的。他正在寻找一个具体的结果,这与我们如何使用这个结果无关。 – 2017-09-20 16:09:31