我正在尝试将模式与可能具有多个模式实例的字符串进行匹配。我需要单独的每个实例。 re.findall()
应该 这样做,但我不知道我做错了什么。
pattern = re.compile('/review: (http://url.com/(\d+)\s?)+/', re.IGNORECASE)
match = pattern.findall('this is the message. review: http://url.com/123 http://url.com/456')
我需要“http://url.com/123”、http://url.com/456 和两个数字 123 和 456 成为 match
列表的不同元素。
我也尝试过 '/review: ((http://url.com/(\d+)\s?)+)/'
作为模式,但没有成功。
最佳答案
使用这个。您需要将“审查”放在捕获组之外才能达到预期的结果。
pattern = re.compile(r'(?:review: )?(http://url.com/(\d+))\s?', re.IGNORECASE)
这给出了输出
>>> match = pattern.findall('this is the message. review: http://url.com/123 http://url.com/456')
>>> match
[('http://url.com/123', '123'), ('http://url.com/456', '456')]
关于Python正则表达式匹配多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17407691/