2011-10-21 99 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 "']