有些混淆了对python正则表达式中组的理解

问题描述 投票:0回答:2

我从一本书中得到了混淆的正则表达组:“使用Python自动化无聊的东西:为初学者提供实用编程”。正则表达式如下:

#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard
# The data of paste from: https://www.nostarch.com/contactus.html
import pyperclip, re

phoneRegex = re.compile(r'''(
     (\d{3}|\(\d{3}\))?              # area code
     (\s|-|\.)?                      # separator
     (\d{3})                         # first 3 digits
     (\s|-|\.)                       # separator  
     (\d{4})                         # last 4 digits
     (\s*(ext|x|ext.)\s*(\d{2,,5}))? # extension
     )''', re.VERBOSE )

# TODO: Create email regex.

emailRegex = re.compile(r'''(
     [a-zA-Z0-9._%+-]+               # username
      @                              # @ symbol
     [a-zA-Z0-9.-]+                  # domian name
     (\.[a-zA-Z]{2,4})               # dot-something
     )''', re.VERBOSE)
# TODO: Find matches in clipboard text.

text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
    **phoneNum = '-'.join ([groups[1], groups[3], groups[5]])
    if groups[8]!= '':
      phoneNum += ' x' + groups[8]**
    matches.append(phoneNum)
print(groups[0])
for groups in emailRegex.findall(text):
    matches.append(groups[0])

# TODO: Copy results to the clipboard.

if len(matches) > 0:
    pyperclip.copy('\n'.join(matches))
    print('Copied to clipboard:')
    print('\n'.join(matches))
else:
    print('No phone number or email addresses found.')

我对groups1 / groups [2] ...... / groups [8]感到困惑。和phoneRegex中有多少组。 group()和groups []之间有什么区别。

粘贴数据来自:[https://www.nostarch.com/contactus.html]

python regex regex-group
2个回答
0
投票

正则表达式可以有组。他们用()表示。组可用于提取可能有用的匹配的一部分。

例如,在电话号码正则表达式中,有9组:

Group  Subpattern
1      ((\d{3}|\(\d{3}\))?(\s|-|\.) (\d{3}) (\s|-|\.)(\d{4})(\s*(ext|x|ext.)\s*(\d{2,,5}))?)
2      (\d{3}|\(\d{3}\))?
3      (\s|-|\.)
4      (\d{3})
5      (\s|-|\.)
6      (\d{4})
7      (\s*(ext|x|ext.)\s*(\d{2,,5}))?
8      (ext|x|ext.)
9      (\d{2,,5})

请注意每个组如何包含在()s中。

groups[x]只是指特定组匹配的字符串。 groups[0]表示由组1匹配的字符串,groups[1]表示与组2匹配的字符串,等等。


0
投票

在正则表达式中,括号()创建所谓的捕获组。每个组都分配一个编号,从1开始。

例如:

In [1]: import re

In [2]: m = re.match('([0-9]+)([a-z]+)', '123xyz')

In [3]: m.group(1)
Out[3]: '123'

In [4]: m.group(2)
Out[4]: 'xyz'

在这里,([0-9]+)是第一个捕获组,而([a-z]+)是第二个捕获组。当你应用正则表达式时,第一个捕获组最终“捕获”字符串123(因为那是它匹配的部分),第二部分捕获xyz

使用findall,它会在字符串中搜索正则表达式匹配的所有位置,并且对于每个匹配,它将捕获的组列表作为元组返回。我鼓励你在ipython玩一下,了解它是如何工作的。另请查看文档:https://docs.python.org/3.6/library/re.html#re.findall

© www.soinside.com 2019 - 2024. All rights reserved.