简体   繁体   中英

Python regex char pattern group

I'm trying to do a regex pattern to match all groups of A.. in a string until the next A. (Python)

For example: DFDAXDJSDSJDAFGCJASDJASAGXCJAD into:

'AXDJSDSJD'
'AFGCJ'
'ASDJ'
'AS'
'AGXCJ'
'AD'

The closest thing I came up with was:

string="DFDAXDJSDSJDAFGCJASDJASAGXCJAD"
r=re.compile('(A.[!=A]*)+')
matchObj = r.findall(string, re.M|re.I)

which returns AF, AS, ASA, AD

Why does it skip the first one? Why doesn't it return all chars until the next A?

You could just split the string on A :

>>> s = "DFDAXDJSDSJDAFGCJASDJASAGXCJAD"
>>> s.split('A')
['DFD', 'XDJSDSJD', 'FGCJ', 'SDJ', 'S', 'GXCJ', 'D']

# add a leading `A` to each match 'on the fly'
>>> [ 'A%s' % s for s in  s.split('A') ]
['ADFD', 'AXDJSDSJD', 'AFGCJ', 'ASDJ', 'AS', 'AGXCJ', 'AD']

Or use an optional positive lookahead :

>>> re.findall('(A[^A]+(?=A)?)', s, re.IGNORECASE | re.MULTILINE)
['AXDJSDSJD', 'AFGCJ', 'ASDJ', 'AS', 'AGXCJ', 'AD']

Or simply (if you do not care about some next A - which is equivalent to saying that it is optional):

>>> re.findall('(A[^A]+)', s, re.IGNORECASE | re.MULTILINE)
['AXDJSDSJD', 'AFGCJ', 'ASDJ', 'AS', 'AGXCJ', 'AD']

I can propose following method:

string="DFDAXDJSDSJDAddaFGCJASDJASAGXCJAD"
r=re.compile('A[^A]*', re.I|re.M)
matchObj = r.findall(string)
matchObj

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