[关闭]
@zhangyu756897669 2017-09-04T15:39:30.000000Z 字数 4203 阅读 594

Python官方文档19.0

python官方文档


正则表达式

正则表达式简介

没有正则表达式的文本模式

假设你想在字符串中找到一个电话号码。你知道这个模式:三个数字,一个连字符,三个数字,连字符和四个数字。 例如: 415-555-4242.

我们使用一个名为isPhoneNumber()的函数来检查一个字符串是否匹配此模式,返回True或False。

  1. def isPhoneNumber(text):
  2. if len(text) != 12:
  3. return False
  4. for i in range(0, 3):
  5. if not text[i].isdecimal():
  6. return False
  7. if text[3] != '-':
  8. return False
  9. for i in range(4, 7):
  10. if not text[i].isdecimal():
  11. return False
  12. if text[7] != '-':
  13. return False
  14. for i in range(8, 12):
  15. if not text[i].isdecimal():
  16. return False
  17. return True
  18. print('415-555-4242 is a phone number:')
  19. print(isPhoneNumber('415-555-4242'))
  20. print('Moshi moshi is a phone number:')
  21. print(isPhoneNumber('Moshi moshi'))

415-555-4242 is a phone number:
True
Moshi moshi is a phone number:
False

  1. def isPhoneNumber(text):
  2. if len(text) != 12:
  3. return False
  4. for i in range(0, 3):
  5. if not text[i].isdecimal():
  6. return False
  7. if text[3] != '-':
  8. return False
  9. for i in range(4, 7):
  10. if not text[i].isdecimal():
  11. return False
  12. if text[7] != '-':
  13. return False
  14. for i in range(8, 12):
  15. if not text[i].isdecimal():
  16. return False
  17. return True
  18. message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
  19. for i in range(len(message)):
  20. chunk = message[i:i+12] #❶
  21. if isPhoneNumber(chunk): #❷
  22. print('Phone number found: ' + chunk)
  23. print('Done')

Phone number found: 415-555-1011
Phone number found: 415-555-9999
Done

用正则表达式寻找文本的模式

创建正则表达式对象

Python中的所有正则表达式函数都在re模块中。

  1. import re

注意:

  1. phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

匹配正则表达式对象

正则表达式对象的search()方法搜索传递给正则表达式的任何匹配的字符串。如果在字符串中找不到正则表达式,则search()方法将返回None。如果找到该模式,则search()方法返回一个Match对象。匹配对象具有一个group()方法,它将从搜索的字符串中返回实际匹配的文本。 (我稍后会解释一下。)

  1. phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
  2. mo = phoneNumRegex.search('My number is 415-555-4242.')
  3. print('Phone number found: ' + mo.group())

Phone number found: 415-555-4242

正则表达式匹配的回顾

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注