[英]How to get all occurances of group with regex in Python?
From code:从代码:
myStr = "one two four five"
myPattern = r'\w*\s(two\s|three\s|four\s)*\w*'
matched = re.search(myPattern, myStr)
if matched:
res = matched.group(1)
print(res)
I get "four ", but I want to get ["two ", "four "]我得到“四”,但我想得到 [“二”,“四”]
How can I do it?我该怎么做?
As all your surrounding word characters are optional, you can use re.findall and assert a whiteapace char to the left and match the trailing one:由于您周围的所有单词字符都是可选的,您可以使用 re.findall 并在左侧声明一个空白字符并匹配尾随字符:
(?<=\s)(?:two|three|four)\s
import re
myStr = "one two four five"
pattern="(?<=\s)(?:two|three|four)\s"
print(re.findall(pattern, myStr))
Output输出
['two ', 'four ']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.