正则表达式查找两个标签之间的单词 [英] Regex to find words between two tags

查看:71
本文介绍了正则表达式查找两个标签之间的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 python 中使用正则表达式在标签之间查找单词?

How can I use regex in python to find words between tags?

s = """<person>John</person>went to<location>London</location>"""
......
.......
print 'person of name:' John
print 'location:' London 

推荐答案

您可以使用 BeautifulSoup 进行此 HTML 解析.

You can use BeautifulSoup for this HTML parsing.

input = """"<person>John</person>went to<location>London</location>"""
soup = BeautifulSoup(input)
print soup.findAll("person")[0].renderContents()
print soup.findAll("location")[0].renderContents()

另外,在 python 中使用 str 作为变量名也不是一个好习惯,因为 str() 在 python 中意味着不同的东西.

Also, it's not a good practice to use str as a variable name in python as str() means a different thing in python.

顺便说一下,正则表达式可以是:

By the way, the regex can be:

import re
print re.findall("<person>(.*?)</person>", input, re.DOTALL)
print re.findall("<location>(.*?)</location>", input, re.DOTALL)

这篇关于正则表达式查找两个标签之间的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆