问题
I need to match the following:
text[ - (option1 option2 .. optionN)]
- text may or may not have spaces
- - is literal and will only appear if there are any option
- can have infinite options
Examples:
rabbit
rabbit white
rabbit - onlyGif
rabbie - onlyGif recent
Currently, I got the following, which works:
^([\w ]+)(?:$|\s-\s(\w+)(?:\s(\w+))?(?:\s(\w+))?)
However, capture at least 3 options, and I need to capture N options. How to do this?
I'm using Python.
回答1:
There is no way to have an unbounded number of capturing groups in Python regexes. However, you can use one regex to match the entire expression and then use a second regex to parse the options. For example:
match = re.match(r'^([\w ]+)(?:\s-((?:\s\w+)+))?$', input)
if match:
text = match.group(1)
if match.group(2):
options = [m.group(0) for m in re.finditer(r'\w+', match.group(2))]
else:
options = []
来源:https://stackoverflow.com/questions/27698616/how-do-the-regular-expression-capture-infinite-groups