Pooja
Pooja

Reputation: 1280

Regular expression to match one from two groups

I want to perform operation like select any one suitable group from two for e.g:

gmail.com|gmail.co.in 

this gives me direct result but how can I write regular expression for python to map email id for above case. Note. I just want to map 3 char after dot or max two group of dot and 2 character

I tried writing regex as :

[\w]+\.?[\w]{3}|[[\w]{2}\.?]{2}

but wont give me expected results

If tried to use () returns group for e.g:[email protected] will return gmail.com but need to retrieve whole email address.

Upvotes: 1

Views: 8006

Answers (3)

jh liu
jh liu

Reputation: 72

I hope this can help you.

email = '[email protected]'
user = email.split('@')[0]
domain = email.split('@')[1]

Upvotes: -1

kvivek
kvivek

Reputation: 3471

Hope this helps.

>>> import re
>>> y = re.search('(?P<user>\w+)@(?P<domain>[\w.]+)', '[email protected]')
>>> print y.group("user"), y.group("domain")
abc gmail.com
>>> y = re.search('(?P<user>\w+)@(?P<domain>[\w.]+)', '[email protected]')
>>> print y.group("user"), y.group("domain")
abc gmail.co.in
>>>

Upvotes: -1

Kasravnd
Kasravnd

Reputation: 107287

You can use the following regex :

\w+@\w+\.((\w{3})|(\w{2}\.\w{2}))

Demo

All you need here is put the first part as \w+@\w+\. then you just need to play with grouping and pipe.so the following pattern:

((\w{3})|(\w{2}\.\w{2}))

will match a string contain 3 word character or (\w{2}\.\w{2}) that means a string with 2 word character then dot then string with 2 word character.

Upvotes: 3

Related Questions