简体   繁体   中英

Optional group following non-greedy group

I'm not completely new to regexes, I've used them on many occasions, but mostly without the 'fancy' stuff like lookaheads and such. I need a single regex that can match the following two patterns:

  1. PrefTextValue13
  2. PrefText

The string 'Pref' is always there and I want to ignore it. 'Text' is a group that I need and it is matched by [\\w\\d_]+ . The string 'Value', when there should be ignored, but when there it must be followed by a number (\\d+) that I need to capture as a group. Both 'Value' and number are optional.

Examples: For case 1) I need to match 'Text' as group 1 and 13 as group 2; for 2) I wan't to match only Text. My attempt (one of many) was:

re.compile("Pref([\w\d_]+)(Value)?(\d+)?") or 
re.compile("Pref([\w\d_]+?)(?:Value)?(?:?=Value)(\d+)?")

but I can't get it right.

Try with this regex:

re.compile(r'^Pref(\w+?)(?:Value(\d+))?$')

Note that [\\w\\d_] is same as \\w .

You have to make Value\\d+ collectively as optional. For that you have to make them a group. But since you don't want to capture them, you can use a non-capturing group. Also, you can make the \\d+ part in it a capturing group, so that you can get that part.

The issue with "Pref(\\w+)(?:Value(\\d+))?" is that, \\w+ will match everything till the end, and satisfy the regex, as Value\\d+ part is optional. So, everything will be captured in \\w+ . So, you have to make it reluctant - \\w+? .

Now, your desired output is in group 1 and group 2 . For the 2 nd case, group 2 will be null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM