如何在python中有效地匹配regex

2024-04-29 12:46:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个代码来匹配美国电话号码格式

所以它应该匹配:

123-333-1111
(123)111-2222
123-2221111

但不应该匹配 12322111号

matchThreeDigits = r"(?:\s*\(?[\d]{3}\)?\s*)"
matchFourDigits = r"(?:\s*[\d]{4}\s*)"
phoneRegex = '('+ '('+  matchThreeDigits + ')' + '-?' +   '('+  matchThreeDigits + ')' + '-?' + '(' + matchFourDigits + ')' +')';
matches = re.findall(re.compile(phoneRegex),line)

问题是我需要确保模式中至少存在()或“-”中的一个(或者它可以是9位数字而不是电话号码)。出于效率考虑,我不想再做一次模式搜索。有没有办法在regex模式本身中容纳这些信息。你知道吗


Tags: 代码re格式line模式电话号码数字效率
3条回答
import re
phoneRegex = re.compile("(\({0,1}[\d]{3}\)(?=[\d]{3})|[\d]{3}-)([\d]{3}[-]{0,1}[\d]{4})")
numbers = ["123-333-1111", "(123)111-2222", "123-2221111", "1232221111", "(123)-111-2222"]
for number in numbers:
    print bool(re.match(phoneRegex, number))

输出

True
True
True
False
False

您可以在这里看到对这个正则表达式的解释:http://regex101.com/r/bA4fH8

可以使用以下正则表达式:

regex = r'(?:\d{3}-|\(\d{3}\))\d{3}-?\d{4}'

假设(123)1112222是可以接受的。你知道吗

|分别充当or,和\(\)逃逸()。你知道吗

像这样的?你知道吗

pattern = r'(\(?(\d{3})\)?(?P<A>-)?(\d{3})(?(A)-?|-)(\d{4}))'

使用它:

import re
regex = re.compile(pattern)
check = ['123-333-1111', '(123)111-2222', '123-2221111', '1232221111']
for number in check:
    match = regex.match(number)
    print number, bool(match)
    if match:
        # show the numbers
        print 'nums:', filter(lambda x: x and x.isalnum(), match.groups())

>>> 
123-333-1111 True
nums: ('123', '333', '1111')
(123)111-2222 True
nums: ('123', '111', '2222')
123-2221111 True
nums: ('123', '222', '1111')
1232221111 False

注意:

您要求解释:(?P<A>-)(?(A)-?|-)

  • (?P<A>-):是一个名为A(?P<NAME> ... )的命名捕获组
  • (?(A)-?|-):检查命名组A是否捕获了某些内容的组,如果捕获了,则执行YES,否则执行NO捕获。(?(NAME)YES|NO)

如果您在Python解释器中执行一个简单的help(re),或者在Google中搜索Python正则表达式,那么所有这些都很容易学会。。。。你知道吗

相关问题 更多 >