這裏有一個答案:
(?<=^([^"]|"[^"]*")*)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