如何在python中匹配以下正则表达式?

时间:2012-10-29 20:31:02

标签: python regex

假设我有以下字符串:

string = "** Hunger is the physical sensation of desiring food.                                      

<br>         Your Hunger Level: Very Hungery<br> Food You Crave: Tomato<br/><br/>"

我希望能够提取出“你的饥饿”和“番茄”。假设无论插入什么特殊字符,我都知道“你的饥饿程度:”和“你渴望的食物”总是不变的。

"Your Hunger Level:" could be: "Very Hungry", "Hungry", "Not So Hungry"
"Food You Crave:" could be: "Tomato", "Rice and Beans", "Corn Soup"

如何使用正则表达式来匹配它?我试过以下,但没有运气......

m = re.match('(.*)([ \t]+)?Your Hunger Level:([ \t]+)?(?P<hungerlevel>.*)(.*)Food You Crave:([ \t]+)?(?P<foodcraving>.*).*', string)                

注意:字符串似乎有很多转义字符如下所示:

string = "** Hunger is the physical sensation of desiring food. <br>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tYour Hunger Level:
Very Hungry \n\t\t\t\t\t\t\t\t<br>\n\t\t\t\t\t\t\t\tFood You Crave: Tomato \n\t\t\t\t\t\t</br>"

3 个答案:

答案 0 :(得分:3)

我会去:

print [map(str.strip, line.split(':')) for line in re.split('<.*?>', string) if ':' in line]
# [['Your Hunger Level', 'Very Hungery'], ['Food You Crave', 'Tomato']]

或者,您可以将其设为dict

lookup = dict(map(str.strip, line.split(':')) for line in re.split('<.*?>', text) if ':' in line)
print lookup['Your Hunger Level']
# 'Very Hungry'

答案 1 :(得分:2)

我绝对同意使用任何类型的解析器,但以下似乎有效。它只是在您的目标词之后开始,直到它到达<(我不认可它用于记录,但希望它可以工作:)):

In [28]: import re

In [29]: s = """** Hunger is the physical sensation of desiring food.
<br>         Your Hunger Level: Very Hungery<br> Food You Crave: Tomato<br/><br/>"""

In [31]: m = re.search(r'Your Hunger Level:([^<]*)<br>.*Food You Crave:([^<]*)', s)

In [32]: m.group(1).strip()
Out[32]: 'Very Hungery'

In [33]: m.group(2).strip()
Out[33]: 'Tomato'

strip()是修剪空格 - 不确定字符串的设置是什么,但这是保守的,以便处理冒号和文本之间没有空格的情况。另外,我建议不要使用Python关键字作为变量名(在这种情况下为string) - 从长远来看,它会让你更容易:)

答案 2 :(得分:0)

  1. 首先,使用解析器解析HTML。您可以使用许多,例如美丽的汤,lxml。
  2. 其次,在文档中搜索<br>标签。
  3. 第三步,搜索所需文本的标签文本,然后返回该标签。