[关闭]
@websec007 2020-07-30T03:20:26.000000Z 字数 753 阅读 799

第7章:模式匹配与正则表达式

python编程快速上手


7.2 使用正则表达式来查找文本模式

7.2.1 字符串匹配检索需求

以下是一个文本字符串,我们需要将其中的号码匹配检索出来;

"Aliec Phone Number: 123-123-1234"

7.2.2 使用正则表达式来实现文本字符串的匹配检索

  1. import re
  1. regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
  1. # 需要被匹配检索的字符串对象:
  2. strings = "Aliec Phone Number: 123-123-1234"
  3. # 使用正则表达式去匹配检索电话号码字符串信息
  4. match = regex.search(strings)
  1. string_match = match.group()
  2. print("Phone-Num >>> {}".format(match_strings))

7.2.3 实例演示说明

  1. # 导入re默认模块
  2. import re
  3. # 以下是一个文本字符串,我们需要将其中的号码匹配检索出来;
  4. strings = "Aliec Phone Number: 123-123-1234"
  5. #(1)创建一个规则表达式对象(regular expression: regex)
  6. regex = re.compile(r'\d\d\d-\d\d\d\-\d\d\d\d')
  7. #(2)使用规则表示对象去匹配检索字符串对象
  8. match = regex.search(strings)
  9. #(3)打印匹配检索结果信息
  10. match_strings = match.group()
  11. print("Phone-Num >>> {}".format(match_strings))
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注