匹配到第二个正则表达式,如果第一个没有匹配

问题描述:

我试图提取使用正则表达式在Python中的HTML标签之间的文本。问题在于有时在字符串中没有HTML标记,所以我希望我的正则表达式匹配整个字符串。到目前为止,我已经得到了标签内文本相匹配的部分:匹配到第二个正则表达式,如果第一个没有匹配

(?<=>).*(?=<\/) 

这符合俄罗斯在标签下面

<a density="sparse" href="http://topics.bloomberg.com/russia/">Russia</a> 

或者,整个字符串将匹配:

Typhoon Vongfong prompted ANA to cancel 101 flights, affecting about 16,600 passengers, the airline said in a faxed statement. Japan Airlines halted 31 flights today and three tomorrow, it said by fax. The storm turned northeast after crossing Okinawa, Japan’s southernmost prefecture, with winds gusting to 75 knots (140 kilometers per hour), according to the U.S. Navy’s Joint Typhoon Warning Center. 

否则我希望它返回字符串中的所有文本。

我已经读了一些关于正则表达式的在线,但我似乎无法让他们工作。如果任何人都能指引我走向正确的方向,那会很棒。提前致谢。

+0

发布一个示例以及预期输出。 – 2014-10-12 06:18:45

+0

我已经添加了它们 – superlizardmo 2014-10-12 06:21:56

+0

使用了一些html解析器。 [例如Beautifulsoup](http://www.crummy.com/software/BeautifulSoup/) – nu11p01n73R 2014-10-12 06:24:13

这是一个解决方法。而不是调整正则表达式,我们调整字符串:

>>> s='<a density="sparse" href="http://topics.bloomberg.com/russia/">Russia</a>' 
>>> re.findall(r'(?<=>)[^<>]*(?=<\/)', s if '>' in s else '>%s</' % s) 
['Russia'] 
>>> s='This is Russia Today' 
>>> re.findall(r'(?<=>)[^<>]*(?=<\/)', s if '>' in s else '>%s</' % s) 
['This is Russia Today'] 

你可以用一个正则表达式来做到这一点。您不需要采取任何解决方法。

>>> import re 
>>> s='<a density="sparse" href="http://topics.bloomberg.com/russia/">Russia</a>' 
>>> re.findall(r'(?<=>)[^<>]+(?=</)|^(?!.*?>.*?</).*', s, re.M) 
['Russia'] 
>>> s='This is Russia Today' 
>>> re.findall(r'(?<=>)[^<>]+(?=</)|^(?!.*?>.*?</).*', s, re.M) 
['This is Russia Today'] 
+0

+1,但我会使用'重新。 S'而不是're.M',因为OP需要整个字符串。 – falsetru 2014-10-12 07:08:18