Python正则表达式

Jef*_*eff 5 python regex

我想从字符串中提取指示符和操作符designator: op1 op2,其中可能有0个或更多操作,并且允许多个空格.我在Python中使用了以下正则表达式

import re
match = re.match(r"^(\w+):(\s+(\w+))*", "des1: op1   op2")
Run Code Online (Sandbox Code Playgroud)

问题是在匹配组中只找到des1和op2,而op1不是.有谁知道为什么?

The groups from above code is
Group 0: des1: op1 op2
Group 1: des1
Group 2:  op2
Group 3: op2

Sin*_*ion 4

两者都被“找到”,但只有一个可以被该团体“捕获”。如果您需要捕获多个组,则需要多次使用正则表达式功能。您可以这样做,首先重写主表达式:

match = re.match(r"^(\w+):(.*)", "des1: op1   op2")
Run Code Online (Sandbox Code Playgroud)

那么你需要提取各个小节:

ops = re.split(r"\s+", match.groups()[1])[1:]
Run Code Online (Sandbox Code Playgroud)