在Python中使用正则表达式匹配字符串的开始和结束
我想用Python从这个网页中提取可解析的引用信息。比如,对于这个页面,我想提取到pl/111/148和pl/111/152。我现在用的正则表达式如下,但它似乎返回了所有在可解析引用之后的内容。可能是个简单的问题,但我对正则表达式还比较陌生。提前谢谢大家。
re.findall(r'^parsable-cite=.*>$',page)
相关问题:
7 个回答
1
虽然这是一个包含HTML内容的JSON字符串,但你仍然可以使用BeautifulSoup来处理它:
soup = BeautifulSoup(htmls);
tags = soup.findAll("external-xref", {"parsable-cite":re.compile("")})
for t in tags:
print t['parsable-cite']
1
1
你看到的这个 .* 是“贪婪”的意思,也就是说它会尽可能多地匹配,包括任意数量的 > 字符以及后面跟着的任何东西。
如果你真正想要的是“直到下一个 > 之前的所有内容”,那么你应该用 [^>]*>,这表示“任意数量的不是 > 的字符,然后是一个 >”。
1
让你的正则表达式变得懒惰:
re.findall(r'^parsable-cite=.*?>$',page)
^
或者使用一个否定类(更推荐):
re.findall(r'^parsable-cite=[^>]*>$',page)
.* 默认是贪婪的,它会尽量匹配尽可能多的内容,然后再判断是否符合条件。
如果你只想获取需要的部分,可以使用捕获组:
re.findall(r'^parsable-cite=([^>]*)>$',page)
不过,从你网页的布局来看,似乎并不需要使用锚点(^ 和 $),除非网站上某种方式去掉了换行符……
2
我强烈推荐使用这个正则表达式,它能捕捉到你想要的内容:
re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page)
解释:
parsable-cite= matches the characters parsable-cite= literally (case sensitive)
\\ matches the character \ literally
\" matches the character " literally
1st Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: Between zero and unlimited times, as few times as possible,
expanding as needed
\\ matches the character \ literally
\" matches the character " literally
\> matches the character > literally
使用?是关键哦;)
希望这对你有帮助。