Python regex search and analysis

In PHP, you can use the preg_match function with the PREG_OFFSET_CAPTURE flag to search for a regular expression in a string and know what follows and what comes first. For example, given the line aaa bbb ccc ddd eee fff , I would like to map-split r'ddd' and have:

 before = 'aaa bbb ccc ' match = 'ddd' after = ' eee fff' 

How to do this in python? Thanks

+7
source share
1 answer

You can use re.split() , but you need to put parentheses around the template to keep the match:

 >>> re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1) ['aaa bbb ccc ', 'ddd', ' eee fff'] 

but in this case you do not need a regex:

 >>> '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 the relevant groups, so you need to be prepared for this or use groups that don't contain a grab wherever you would otherwise use parentheses for priority:

 >>> re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1) ['aaa bbb ccc ', 'ddd', 'd', ' eee fff'] 
+12
source

All Articles