Search code examples
pythonregexpython-re

replace before and after a string using re in python


i have string like this 'approved:rakeshc@IAD.GOOGLE.COM'

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:rakeshc@IAD.GOOGLE.COM'.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:rakeshc@IAD.GOOGLE.COM'
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


Solution

  • Here is a regex one-liner:

    inp = "approved:rakeshc@IAD.GOOGLE.COM"
    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.