为什么RegExr在线工具中的模式与pythons re模块的模式不一样?我使用RegExr中的相同模式来获取re.search()和re.match()中的模式参数
这是我的测试字符串:“c 4:4 sd:4 31:3”
这是RegExr在线工具输出的内容:['4:4','31:3']
pattern_match.py是我的python脚本
import re
#helper function
def displaymatch(match):
if match is None:
return None
return '<Match: %r, groups=%r>' % (match.group(), match.groups())
user_input = raw_input("enter <number>:<number> ")
regex_pattern = r'[0-9]+:[0-9]+'
is_match = re.match(regex_pattern, user_input)
is_search = re.search(regex_pattern, user_input)
print "match function " + str(is_match)
print "search function " + str(is_search)
print(displaymatch(is_search))
答案 0 :(得分:1)
由于您的模式中没有capturing groups,因此groups()
方法对您没有多大帮助,group()
对match
的帮助不大(匹配来自开始)和search
(匹配任何地方)只产生第一场比赛。 re.findall
将返回所有非重叠匹配子字符串的列表:
> import re
> print re.findall(r'[0-9]+:[0-9]+', 'c 4:4 sd:4 31:3')
['4:4', '31:3']
https://docs.python.org/2/howto/regex.html#regular-expression-howto
答案 1 :(得分:0)
i)在正则表达式网站中,您正在启用g
标记。所以它找到了所有的比赛。如果没有g
标记,请参阅 here 。
ii)re.match
返回None
,因为它只在字符串的开头找到匹配。
iii)re.search
将找到第一场比赛并返回。所以你得到4:4
。
iv)您需要使用re.findall(regex_pattern, user_input)
查找所有匹配项。