我正在解析一个字符串,我知道它肯定只包含我想要解析的以下不同短语:
'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']
关于python - 本示例中使用什么正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587942/