In PHP one can use the function preg_match
with the flag PREG_OFFSET_CAPTURE
in order to search a regex patter within a string and know what follows and what comes first. For example, given the string aaa bbb ccc ddd eee fff
, I'd like to match-split r'ddd'
and have:
before = 'aaa bbb ccc '
match = 'ddd'
after = ' eee fff'
How to do this in python? Thanks
You can use re.split()
but you need to put parentheses around the pattern so as to save the match:
>>> re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)
['aaa bbb ccc ', 'ddd', ' eee fff']
but in this case you don't need a regex at all:
>>> 'aaa bbb ccc ddd eee fff'.partition('ddd')
('aaa bbb ccc ', 'ddd', ' eee fff')
Edit: I should probably also mention that with re.split you will get all of the matching groups, so you need to be prepared for that or use non-capturing groups everywhere you would otherwise use parentheses for precedence:
>>> re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)
['aaa bbb ccc ', 'ddd', 'd', ' eee fff']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With