如何修复此正则表达式

时间:2019-10-03 09:03:24

标签: regex python-3.x

我是python的新手,目前正在学习regex,我尝试了以下代码,并发生了一些错误,请有人可以为您提供建议。

#! python3
import re, pyperclip

phoneRegex = re.compile(r'''

((\d\d\d) | (\(\d\d\d\)))?
\s|- 
\d\d\d
- 
\d\d\d\d
((ext(\.)?\s)|x)
(\d{2,5}))? 

''', re.VERBOSE)


emailRegex = re.compile(r'''

[a-zA-Z0-9_.+]+
@
[a-zA-Z0-9_.+]+

''',re.VERBOSE)


text = pyperclip.paste()
extractedPhone = phoneRegex.findall(text)
extractedemail = emailRegex.findall(text)

print(extractedphone)
print (extractedemail) 

输出:

Traceback (most recent call last):
  File "C:/Users/Bane/Desktop/RegexProject.py", line 14, in <module>
    ''', re.VERBOSE)
  File "C:\Users\Bane\AppData\Local\Programs\Python\Python37-32\lib\re.py", line 234, in compile
    return _compile(pattern, flags)
  File "C:\Users\Bane\AppData\Local\Programs\Python\Python37-32\lib\re.py", line 286, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\Users\Bane\AppData\Local\Programs\Python\Python37-32\lib\sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
  File "C:\Users\Bane\AppData\Local\Programs\Python\Python37-32\lib\sre_parse.py", line 944, in parse
    raise source.error("unbalanced parenthesis")
re.error: unbalanced parenthesis at position 80 (line 9, column 10)

我复制的文档:

  

主席Barbara Jones博士x107 870-864-7190 brjones@southark.edu   执行助理Susan Jordan女士x107 870-864-7190 sjordan@southark.edu   财务副总裁兼Belinda Aaron博士x147 870-864-7122 baaron@southark.edu

1 个答案:

答案 0 :(得分:0)

错误line 9, column 10将您引向有问题的正则表达式行和字符位置。

您的括号内没有匹配的内容。

(\d{2,5}))? <- the final closing parenthesis is missing an opening parenthesis

请参见https://regex101.com/r/BosI4u/1