2011-10-21 24 views
0

我有來自外部的我的應用程序字符串和可能看起來像這些引號:如何正確處理正則表達式匹配

Prefix content. "Some content goes here". More contents without quotes. 
Prefix content. "Another "Additional" goes here". More contents without quotes. 
Prefix content. "Just another "content". More contents without quotes. 

的關鍵值得注意的是,弦都加上引號,我需要處理這些正確引用。其實我需要捕捉引號內的所有內容。我嘗試了.*(".*").*.*(".+").*等模式,但它們似乎只捕捉兩個最接近的引號之間的內容。

+3

目前還不清楚你想要捕獲哪些內容。例如,在#3行中,你想匹配什麼? – FailedDev

回答

2

看起來你只是想從第一個報價到最後一個報價,即使有其他報價之間的所有內容。這應該足夠了:

".*" 

領先的,而且從來沒有需要你的正則表達式尾隨.*,以及領先的一個被扭曲的結果。它最初會消耗整個輸入,然後退回足夠遠以讓其餘的正則表達式匹配,這意味着(".*")只會匹配最後兩個引號。

你也不需要括號。你之後的字符串部分現在是整個比賽,所以你可以用group(0)而不是group(1)來檢索它。如果有可能在字符串中換行,你想匹配,也可以將其更改爲:

(?s)".*" 

.元字符一般不會匹配換行符,但(?s)打開DOTALL模式的其餘部分正則表達式。


編輯:我忘了提,你應該使用search()方法在這種情況下,不match()match()僅當在輸入的最開始處找到匹配時才起作用,就好像您已添加起始錨點(例如,^".*")。 search()執行更傳統的正則表達式匹配,其中匹配可以出現在輸入中的任何地方。 (ref

0

編輯:我現在看到另一個答案,我可能誤解了你的問題。

嘗試修改此

.*(".+").* 

.*?(".+?") 

?將使得搜索非貪婪,並會盡快停止,因爲它會找到下一個匹配的字符(即引號)。我還在末尾刪除了*,因爲它會匹配字符串的其餘部分(不管引號是什麼)。如果您想要匹配空引號以及將+更改爲*。使用re.findall從報價中提取所有內容。

PS:我認爲你的最後一行是錯誤的,因爲它沒有匹配的引號。

+0

如果我已經正確理解他的目標,那麼非貪婪的匹配將失敗第2行和第3行 – Nate

+0

@Nate我剛剛刪除了*。 re.findall適用於第二行,第三行沒有匹配的引號,所以我認爲它只是被粘貼錯誤。 – rplnt

1

我不確定你想要提取什麼,所以我猜測。我建議使用partitionrpartition字符串方法。

這是做你想做的嗎?

>>> samples = [ 
... 'Prefix content. "Some content goes here". More contents without quotes.', 
... 'Prefix content. "Another "Additional" goes here". More contents without quotes.', 
... 'Prefix content. "Just another "content". More contents without quotes.', 
... ] 
>>> def get_content(data): 
... return data.partition('"')[2].rpartition('"')[0] 
... 
>>> for sample in samples: 
... print get_content(sample) 
... 
Some content goes here 
Another "Additional" goes here 
Just another "content 
0

我不太確定這是你想達到的目標。 來自re模塊的finditer方法在這裏可能會有所幫助。

>>> import re 
>>> s = '''Prefix content. "Some content goes here". More contents without quotes. 
...  Prefix content. "Another "Additional" goes here". More contents without quotes. 
...  Prefix content. "Just another "content". More contents without quotes.''' 
>>> pattern = '".+?"' 
>>> results = [m.group(0) for m in re.finditer(pattern, s)] 
>>> print results 
['"Some content goes here"', '"Another "', '" goes here"', '"Just another "']