Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace before and after a string using re in python

i have string like this 'approved:[email protected]'

i would like extract text after ':' and before '@' in this case the test to be extracted is rakeshc

it can be done using split method - 'approved:[email protected]'.split(':')[1].split('@')[0]

but i would want this be done using regular expression.

this is what i have tried so far.

import re
iptext = 'approved:[email protected]'
re.sub('^(.*approved:)',"", iptext)  --> give everything after ':'
re.sub('(@IAD.GOOGLE.COM)$',"", iptext)  --> give everything before'@'

would want to have the result in single expression. expression would be used to replace a string with only the middle string

like image 982
rakesh Avatar asked Feb 24 '26 20:02

rakesh


1 Answers

Here is a regex one-liner:

inp = "approved:[email protected]"
output = re.sub(r'^.*:|@.*$', '', inp)
print(output)  # rakeshc

The above approach is to strip all text from the start up, and including, the :, as well as to strip all text from @ until the end. This leaves behind the email ID.

like image 164
Tim Biegeleisen Avatar answered Feb 27 '26 09:02

Tim Biegeleisen