2012-07-23 80 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) 

,你可能要細化一點的字邊界等等。但是這應該讓你你想去的地方,而且是一個明確的讀取樣本。

相關問題