我正在解析一个字符串,我知道它肯定只会包含以下我要解析的不同短语:
'Man of the Match'
'Goal'
'Assist'
'Yellow Card'
'Red Card'
我正在解析的字符串可能包含所有元素,从没有以上元素到所有元素(即被解析的字符串可以是从 None 到“Man of the Match Goal Assist Yellow Card Red Card”的任何内容。
对于那些了解足球的人来说,您还会意识到“进球”和“助攻”这两个元素在理论上可以重复无限次。元素“黄牌”也可以重复 0、1 或 2 次。
我已经构建了以下正则表达式(其中“incident1”是正在解析的字符串),我相信它会返回无限数量的所有前面的正则表达式,但是我得到的只是单个实例:
regex1 = re.compile("Man of the Match*", re.S)
regex2 = re.compile("Goal*", re.S)
regex3 = re.compile("Assist*", re.S)
regex4 = re.compile("Red Card*", re.S)
regex5 = re.compile("Yellow Card*", re.S)
mysearch1 = re.search(regex1, incident1)
mysearch2 = re.search(regex2, incident1)
mysearch3 = re.search(regex3, incident1)
mysearch4 = re.search(regex4, incident1)
mysearch5 = re.search(regex5, incident1)
#print mystring
print "incident1 = ", incident1
if mysearch1 is not None:
print "Man of the match = ", mysearch1.group()
if mysearch2 is not None:
print "Goal = ", mysearch2.group()
if mysearch3 is not None:
print "Assist = ", mysearch3.group()
if mysearch4 is not None:
print "Red Card = ", mysearch4.group()
if mysearch5 is not None:
print "Yellow Card = ", mysearch5.group()
只要在字符串中遇到的每个元素只有一个实例,这种方法就可以工作,但是,如果一名球员进了多个球,则此代码仅返回一个“Goal”实例。
谁能看出我做错了什么?
请您参考如下方法:
你可以尝试这样的事情:
import re
s = "here's an example Man of the Match match and a Red Card match, and another Red Card match"
patterns = [
'Man of the Match',
'Goal',
'Assist',
'Yellow Card',
'Red Card',
]
repattern = '|'.join(patterns)
matches = re.findall(repattern, s, re.IGNORECASE)
print matches # ['Man of the Match', 'Red Card', 'Red Card']
