简体   繁体   中英

capturing repeating groups with reg ex in python

Ex. "steve && chris || joe && george"

Group[0] = steve && chris 
Group[1] = joe && george

I can find the first group (.*?)([|]{2}) but how can find the next group.

keep in mind i want it to be dynamic. String will grow in the same pattern. For Ex.

"steve && chris || joe && george || sep && geo"

A non Regex solution can be using str.split

>>> s = "steve && chris || joe && george"
>>> tmp = s.split('||')
>>> groups = map(str.strip,tmp)
>>> groups
['steve && chris', 'joe && george']

The map and str.strip is used here to cleanse the groups

and it is dynamic also

>>> s =  "steve && chris || joe && george || sep && geo"
>>> tmp = s.split('||')
>>> groups = map(str.strip,tmp)
>>> groups
['steve && chris', 'joe && george', 'sep && geo']

Do note that basic string functions work out faster than RegEx solutions

Perhaps the best way is to just use the Python split function:

s = 'steve && chris || joe && george'
s.split(' || ')  # returns ['steve && chris', 'joe && george']

However, to use a regex, you could do the following:

import re
# group all strings separated by `|` and at least length 1
arr = re.findall('[^|]{1,}', "steve && chris || joe && george || sep && geo")
print(arr)  # ['steve && chris ', ' joe && george ', ' sep && geo']

If you are planning to use regex , you can use the following:

(\w*\ ?&&\ ?\w*)

DEMO

You can also use python split function for this.

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