replace before and after a string using re in python

Viewed 140

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

4 Answers

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.

Use a capture group to copy the part between the matches to the result.

result = re.sub(r'.*approved:(.*)@IAD\.GOOGLE\.COM$', r'\1', iptext)

Hope this works for you:

import re

input_text = "approved:rakeshc@IAD.GOOGLE.COM"

out = re.search(':(.+?)@', input_text)
if out:
    found = out.group(1)
    print(found)

You can use this one-liner:

re.sub(r'^.*:(\w+)@.*$', r'\1', iptext)

Output:

rakeshc
Related