简体   繁体   English

如何在Python上使用正则表达式删除括号?

[英]How to remove parenthesis using regex on Python?

I have string like this: 我有这样的字符串:

Alex Jatt, (alex.jatt@domain.com)

amd I'm trying to extract only email address using regex like so: 我想尝试使用正则表达式提取电子邮件地址,如下所示:

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

but print p command prints (alex.jatt@domain.com) 但打印p命令打印(alex.jatt@domain.com)

How can I modify this regex to get rid of parenthesis? 如何修改此正则表达式以摆脱括号?

without regex solution: 没有regex解决方案:

>>> strs="Alex Jatt, (alex.jatt@domain.com)"
>>> strs.split(',')[1].strip().strip("()")
'alex.jatt@domain.com'

re.search allows you to pull matched groups out of the regular expression match. re.search允许您从正则表达式匹配中提取匹配的组。 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. 在您的情况下,您可能希望使用p.group(1)来提取第一个带括号的匹配,该匹配应该是您拥有的正则表达式中的电子邮件。

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, alex.jatt@domain.com'

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. 无论哪种方式都可行。

I think you've been changing the code before pasting it in here. 我认为你在修改代码之前一直在改变代码。

If I do: 如果我做:

>>> import re
>>> c="Alex Jatt, (alex.jatt@domain.com)"
>>> p = re.search('\((.*?)\)', c)
>>> print p
<_sre.SRE_Match object at 0x10bd68af8>

You want to look at the groups: 你想看看这些组:

>>> import re
>>> c="Alex Jatt, (alex.jatt@domain.com)"
>>> p = re.search('\((.*?)\)', c)
>>> print p.groups()[0]
alex.jatt@domain.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM