开发者

python regex grouping

Given string s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'

I would like to get this output: (C /something_3),/,(D /something_4)(D /something_5)

开发者_运维问答I keep matching the whole string s, instead of getting above substring.

I am using re.search(r'(\(C.*\)),/,(\(D.*\))+')

Any help is appreciated...


You're just about there - re.search(r'(\(C.*\)),/,(\(D.*\))+', s).group() will get you what you want.

>>> import re
>>> s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'
>>> re.search(r'(\(C.*\)),/,(\(D.*\))+', s).group()
'(C /something_3),/,(D /something_4)(D /something_5)'

Are you wanting to further split that in groups?


Using Python 2.7, I get the exact result you're after:

import re
s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'
m = re.search(r'(\(C.*\)),/,(\(D.*\))+', s)

s[m.start():m.end()] == '(C /something_3),/,(D /something_4)(D /something_5)'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜