[英]Beginners Python: Regex & Phone Numbers
通過初學者Python書籍,我有兩個相當簡單的事情,我不明白,並希望有人在這里可以提供幫助。
本書中的示例使用正則表達式從剪貼板中接收電子郵件地址和電話號碼,並將它們輸出到控制台。 代碼如下所示:
#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard.
import pyperclip, re
# Create phone regex.
phoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? #[1] area code
(\s|-|\.)? #[2] separator
(\d{3}) #[3] first 3 digits
(\s|-|\.) #[4] separator
(\d{4}) #[5] last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #[6] extension
)''', re.VERBOSE)
# Create email regex.
emailRegex = re.compile(r'''(
[a-zA-Z0-9._%+-]+
@
[\.[a-zA-Z0-9.-]+
(\.[a-zA-Z]{2,4})
)''', re.VERBOSE)
# 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)
for groups in emailRegex.findall(text):
matches.append(groups[0])
# 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 numbers of email addresses found')
好的,首先,我真的不了解phoneRegex對象。 該書提到添加括號將在正則表達式中創建組。
如果是這種情況,我在評論中假設的索引值是否錯誤,並且索引中是否真的有兩個組標記為一個? 或者如果它們是正確的,那么群組[7,8]在下面的匹配循環中提到的電話號碼是什么?
其次,為什么emailRegex使用列表和元組的混合,而phoneRegex主要使用元組?
編輯1
感謝到目前為止的答案,他們一直很有幫助。 盡管如此,第一部分還是有點困惑。 應該有像rock321987的答案這樣的八個索引還是像sweaver2112那樣的九個索引?
編輯2
回答,謝謝。
每個左邊的開口(
標記一個捕獲組的開頭,你可以嵌套它們:
( #[1] around whole pattern
(\d{3}|\(\d{3}\))? #[2] area code
(\s|-|\.)? #[3] separator
(\d{3}) #[4] first 3 digits
(\s|-|\.) #[5] separator
(\d{4}) #[6] last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #[7,8,9] extension
)
您應該在這里使用命名組 (?<groupname>pattern)
,以及僅捕獲不捕獲任何內容的parens (?:pattern)
。 請記住,您應該捕獲量化的構造,而不是量化捕獲的構造:
(?<areacode>(?:\d{3}|\(\d{3}\))?)
(?<separator>(?:\s|-|\.)?)
(?<exchange>\d{3})
(?<separator2>\s|-|\.)
(?<lastfour>\d{4})
(?<extension>(?:\s*(?:ext|x|ext.)\s*(?:\d{2,5}))?)
( #[1] around whole pattern
(\d{3}|\(\d{3}\))? #[2] area code
(\s|-|\.)? #[3] separator
(\d{3}) #[4] first 3 digits
(\s|-|\.) #[5] separator
(\d{4}) #[6] last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? #[7] extension
<----------> <------->
^^ ^^
|| ||
[8] [9]
)
第二個問題
你理解它是完全錯誤的。 你正在混合python與正則表達式。 在正則表達式
[]
字符類(而不是列表)
()
捕獲組(而不是元組)
所以內部的任何內容都與python中的list
和tuple
無關。 正則表達式可以被視為一種語言, ()
, []
等是正則表達式的一部分
對於你的問題的第一部分,請參閱sweaver2112的答案
對於第二部分,使用列表和元組。 在Regex \\ d中與[0-9]相同,它更容易編寫。 同樣,他們可以為[a-zA-Z]編寫\\ w但是不會考慮特殊字符或0-9使它更容易放[a-zA-Z0-9.-]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.