3

I have string like this:

Alex Jatt, ([email protected])

amd I'm trying to extract only email address using regex like so:

p = re.search('\((.*?)\)', c)

but print p command prints ([email protected])

How can I modify this regex to get rid of parenthesis?

5 Answers 5

3

re.search allows you to pull matched groups out of the regular expression match. In your case, you would want to use p.group(1) to extract the first parenthesized match, which should be the email in the regular expression you have.

Sign up to request clarification or add additional context in comments.

Comments

3

without regex solution:

>>> strs="Alex Jatt, ([email protected])"
>>> strs.split(',')[1].strip().strip("()")
'[email protected]'

Comments

3

With join also you can do it..

a= ''.join(c for c in a if c not in '()')

or with regex..

In[20]: import re

In[21]: name= re.sub('[()]', '', a)

In [22]: name
Out[22]: 'Alex Jatt, [email protected]'

Comments

2

use a look ahead and a look behind to make sure that the parenthesis are there, but to prevent you from capturing them.

p = re.search('(?<=\().*?(?=\))', c)

or you could just access the capture group instead of the whole regex.

p = re.search('\((.*?)\)', c).group(1)

either way would work.

Comments

0

I think you've been changing the code before pasting it in here.

If I do:

>>> import re
>>> c="Alex Jatt, ([email protected])"
>>> p = re.search('\((.*?)\)', c)
>>> print p
<_sre.SRE_Match object at 0x10bd68af8>

You want to look at the groups:

>>> import re
>>> c="Alex Jatt, ([email protected])"
>>> p = re.search('\((.*?)\)', c)
>>> print p.groups()[0]
[email protected]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.