How do the regular expression capture infinite groups?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 03:42:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!