为什么RegExr工具和python re模块与我的字符串不匹配?

时间:2016-05-22 17:11:55

标签: python regex module

为什么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))

2 个答案:

答案 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)查找所有匹配项。