Python 3.x 自动化无聊的东西:电话号码和电子邮件提取器
我试图修改代码以提取印度电话号码,但输出似乎将每个电话号码打印两次。电子邮件部分工作正常,但我在打印手机号码时没有得到想要的输出Python 3.x 自动化无聊的东西:电话号码和电子邮件提取器,python-3.x,regex,Python 3.x,Regex,我试图修改代码以提取印度电话号码,但输出似乎将每个电话号码打印两次。电子邮件部分工作正常,但我在打印手机号码时没有得到想要的输出 #! python3 # PhoneandEmail.py - Finds all the phone numbers and emails in the clipboard import pyperclip, re phoneRegex = re.compile(r'''( (\+)? (\s
#! python3
# PhoneandEmail.py - Finds all the phone numbers and emails in the clipboard
import pyperclip, re
phoneRegex = re.compile(r'''(
(\+)?
(\s)?
(91)?
(\s)?
(\d{5})
(\s)?
(\d{5})
)''', re.VERBOSE)
emailRegex = re.compile(r'''(
[a-zA-Z0-9_%+-]+ # username
@ # @ symbol
[a-zA-Z0-9.-]+ # domain name
(\.[a-zA-Z]{2,4})# dot-something
)''', re.VERBOSE)
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
phoneNum = ''.join(groups)
matches.append(phoneNum)
for groups in emailRegex.findall(text):
matches.append(groups[0])
if len(matches) > 0 :
pyperclip.copy('\n'.join(matches))
print('coppied to clipboard')
print('\n'.join(matches))
else:
print('nothing found')
您正在查找捕获组并在phoneNum中加入它们
现在,捕获组(\+)
,(\s)
,(91)
,(\s)
,(\d{5})
,(\s)
,和(\d{5})
一起组成了一个电话号码。
大捕获群(\+)(\s)?(91)?(\s)?(\d{5})(\s)?(\d{5}))
还捕获电话号码。因此,电话号码会打印两次。谢谢,但如何解决此问题?请删除外部捕获组
phoneRegex=re.compile(r''(\+)(\s)?(\s)?(\d{5})(\s)?(\d{5}'),re.VERBOSE)
另一种方法:您也可以使内部组不捕获:phoneRegex=re.compile(r''((?:\+)(?:\s)?(?:91)?(?::\s)?(?:\d{5})(?:\s)?(?:\d{5})re.VERBOSE>。您可以使用(?:)
使组不捕获。
phoneRegex = re.compile(r'''(
(\+)?
(\s)?
(91)?
(\s)?
(\d{5})
(\s)?
(\d{5})
)''', re.VERBOSE)