【Python正则表达式】:文本解析与模式匹配

打印 上一主题 下一主题

主题 822|帖子 822|积分 2466

1.正则表达式


正则表达式面向什么样的题目?


  • 1、判定一个字符串是否匹配给定的格式(判定是不是邮箱或者电话号码) 数据校验
  • 2、从一个字符串里面根据指定规则提取信息(抓取页面中的链接或者别的信息) 数据提取
2. re模块

正则表达式写出来后需要使用,那么需要使用re模块举行使用,提取及验证等操纵,re模块为内置模块,使用时需要导包 ----- import re


  • 常用方法分为:findall, match, search
  1. # re.findall() 是 Python 中 re 模块提供的一个函数,用于在字符串中查找所有满足指定正则表达式的子串,并返回一个列表。下面我将详细介绍 re.findall() 的使用方法及其相关参数。
  2. """
  3. re.findall(pattern, string, flags=0)
  4. pattern 是要匹配的正则表达式;
  5. string 是要在其中进行匹配的字符串;
  6. flags 参数可以指定正则表达式的匹配模式,如是否忽略大小写等。
  7. """
  8. import re
  9. # 定义正则表达式  '\d+',它可以匹配一个或多个数字字符
  10. pattern = r'\d+'
  11. # 定义字符串
  12. string = 'The price of the apple is 2 dollars, and the price of the orange is 1 dollar.'
  13. # 使用 findall() 函数查找数字
  14. result = re.findall(pattern, string)
  15. # 输出结果
  16. print(result)
  17. # ['2', '1']
  18. """
  19. # ====== findall =======
  20. #  re.finall(目标数据,目标字符串)
  21. #      在目标字符串中找出所有符合目标数据的数据,符合条件的数据放入列表中
  22. #      没有就返回空列表
  23. """
复制代码


  • re.findall()返回的是一个列表,列表中的每个元素都是字符串类型。假如正则表达式中包含分组,则返回的列表中同样包含分组捕获的内容。
  • 假如正则表达式中包含多个子表达式,则返回的列表中会按照整个正则表达式的优先级次序分列子表达式的匹配结果。
  • 当正则表达式中包含重复字符集(如 * 或 +)时,返回的是一个包含所有匹配到的子串的列表。假如渴望返回所有匹配到的重复字符集中单个重复的内容,可以使用非贪婪模式的量词(如 *? 和 +?)或分组语法。
  • 假如要精确匹配某个字符串,应该使用锚定字 ^ 和 $ 来限定匹配范围。否则大概会匹配到意想不到的内容。
  1. # re.match() 是 Python 中 re 模块提供的一个函数,用于在字符串的开头匹配正则表达式,并返回一个 Match 对象。下面我将详细介绍 re.match() 的使用方法及其相关参数。
  2. """
  3. re.match(pattern, string, flags=0)
  4. pattern 是要匹配的正则表达式;
  5. string 是要在其中进行匹配的字符串;
  6. flags 参数可以指定正则表达式的匹配模式,如是否忽略大小写等。
  7. """
  8. import re
  9. # 定义正则表达式
  10. pattern = r'\d+'
  11. # 定义字符串
  12. string = 'The price of the apple is 2 dollars.'
  13. # 使用 match() 函数查找数字
  14. match_result = re.match(pattern, string)
  15. # 输出匹配结果
  16. if match_result:
  17.     print("匹配成功:", match_result.group())
  18. else:
  19.     print("匹配失败")
  20. # 匹配失败
  21. """
  22. # ====== match =======
  23. # re.match(pattern, string, flags=0)
  24. #   pattern     匹配的正则表达式
  25. #   string      要匹配的字符串
  26. #   flags       标志符指定,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等
  27. #        必须从字符串开头匹配!
  28. #        match方法尝试从字符串的起始位置匹配一个模式,
  29. #        如果不是起始位置匹配成功的话,match()就返回none
  30. # 返回值为对象
  31. # group():查看匹配字符
  32. # span:查看匹配数据的索引取值区间
  33. """
复制代码

定义了一个正则表达式 r’\d+',它可以匹配一个或多个数字字符。然后定义了一个字符串 string,需要在其中查找与正则表达式匹配的子串。最后使用 re.match() 函数在字符串开头查找符合正则表达式规则的子串,并返回一个 Match 对象。假如匹配乐成,则输出匹配到的结果;否则输出“匹配失败”。

  • re.match() 只会匹配到字符串的开头。假如想要在整个字符串中匹配正则表达式,应该使用 re.search() 或 re.findall()。
  • 假如 Match 对象存在,则可以通过调用 group() 方法获取匹配到的子串;假如不存在,则阐明匹配失败。
  • 在使用正则表达式时,需要根据具体环境思量各种特别字符和操纵符的寄义和使用方式,并举行适当的转义处理或括号分组。
  1. # re.search() 是 Python 中 re 模块提供的一个函数,用于在字符串中搜索与正则表达式匹配的子串,并返回一个 Match 对象。
  2. """
  3. re.search(pattern, string, flags=0)
  4. 其中,pattern 是要匹配的正则表达式;
  5. string 是要在其中进行搜索的字符串;
  6. flags 参数可以指定正则表达式的匹配模式,如是否忽略大小写等。
  7. """
  8. import re
  9. # 定义正则表达式
  10. pattern = r'\d+'
  11. # 定义字符串
  12. string = 'The price of the apple is 2 dollars.'
  13. # 使用 search() 函数查找数字
  14. search_result = re.search(pattern, string)
  15. # 输出匹配结果
  16. if search_result:
  17.     print("匹配成功:", search_result.group())
  18. else:
  19.     print("匹配失败")
  20. # 匹配成功: 2
  21. # group:查看匹配字符
  22. # span:查看匹配数据的索引取值区间
复制代码

起首定义了一个正则表达式 r’\d+',它可以匹配一个或多个数字字符。然后定义了一个字符串 string,需要在其中搜索符合正则表达式规则的子串。最后使用 re.search() 函数在字符串中搜索第一个符合正则表达式规则的子串,并返回一个 Match 对象。假如匹配乐成,则输出匹配到的结果;否则输出“匹配失败”。

  • re.search() 只会搜索到第一个符合正则表达式规则的子串,并返回一个 Match 对象。假如想要搜索所有符合规则的子串,则应该使用 re.findall()
  • 假如 Match 对象存在,则可以通过调用 group() 方法获取匹配到的子串;假如不存在,则阐明匹配失败。
  • 在使用正则表达式时,需要根据具体环境思量各种特别字符和操纵符的寄义和使用方式,并举行适当的转义处理或括号分组。
3.修饰符

修饰符(可选标志–flags)
修饰符描述re.I使匹配对巨细写不敏感re.L做当地化识别(locale-aware)匹配re.M多行匹配,影响 ^ 和 $re.S使 . 匹配包括换行在内的所有字符re.U根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.re.X该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。
  1. # re.I 或 re.IGNORECASE:表示忽略大小写匹配
  2. import re
  3. # 定义正则表达式,使用忽略大小写(re.I)匹配模式
  4. pattern = r'hello'
  5. # 定义字符串
  6. string = 'Hello, world!'
  7. # 使用 search() 函数查找
  8. search_result = re.search(pattern, string, re.I)
  9. # 输出匹配结果
  10. if search_result:
  11.     print("匹配成功:", search_result.group())
  12. else:
  13.     print("匹配失败")
复制代码

正则表达式 pattern 用于匹配字符串中的单词 ‘hello’,但是使用了巨细写不敏感的匹配模式 re.I,因此可以匹配到大写的单词 ‘Hello’。

  1. # re.M 或 re.MULTILINE:表示进行多行匹配。
  2. import re
  3. # 定义正则表达式,使用多行(re.M)匹配模式
  4. pattern = r'^hello'
  5. # 定义字符串
  6. string = 'Hello\nhello, world!'
  7. # 使用 findall() 函数查找所有匹配项
  8. result = re.findall(pattern, string, re.M)
  9. # 输出结果
  10. print(result)
复制代码

正则表达式 pattern 用于匹配字符串中以单词 ‘hello’ 开头的行,使用了多行匹配模式 re.M,因此可以匹配到两行中以 ‘hello’ 开头的字符串。

  1. # re.S 或 re.DOTALL:表示可以匹配任意字符,包括换行符。
  2. import re
  3. # 定义正则表达式,使用 . 匹配任意字符(含换行符)的模式
  4. pattern = r'.*'
  5. # 定义字符串
  6. string = 'Hello\nworld!'
  7. # 使用 search() 函数查找
  8. search_result = re.search(pattern, string, re.S)
  9. # 输出匹配结果
  10. if search_result:
  11.     print("匹配成功:", search_result.group())
  12. else:
  13.     print("匹配失败")
复制代码

正则表达式 pattern 用于匹配字符串中的任何字符,包括换行符。由于使用了 re.S 修饰符,因此可以匹配到整个字符串。

  1. # re.X 或 re.VERBOSE:表示进行可读性更好的正则表达式编写。
  2. import re
  3. # 定义正则表达式,使用换行和注释来分隔模式
  4. pattern = r"""
  5.     \d+      # 表示匹配一个或多个数字字符
  6.     \s*      # 表示匹配零个或多个空格字符
  7.     dollars  # 表示匹配单词 'dollars'
  8. """
  9. # 定义字符串
  10. string = 'The price is 2 dollars.'
  11. # 使用 search() 函数查找
  12. search_result = re.search(pattern, string, re.X)
  13. # 输出匹配结果
  14. if search_result:
  15.     print("匹配成功:", search_result.group())
  16. else:
  17.     print("匹配失败")
复制代码

正则表达式 pattern 用于匹配字符串中的价值和货币单位,使用了 re.X 修饰符来举行可读性更好的正则表达式编写。通过注释和换行等方式,可以将正则表达式分解为多个易于理解的部分,使得正则表达式变得更加清楚和易于维护。

  1. # re.U 或 re.UNICODE:表示使用 Unicode 字符集进行匹配。
  2. import re
  3. # 定义 Unicode 字符串
  4. unicode_str = u'Hello, 你好!'
  5. # 定义 ASCII 字符串
  6. ascii_str = 'Hello, world!'
  7. # 定义正则表达式
  8. pattern = r'\w+'
  9. # 使用 re.U 修饰符进行匹配
  10. match_result1 = re.findall(pattern, unicode_str, re.U)
  11. print("使用 re.U 修饰符的匹配结果:", match_result1)
  12. # 不使用 re.U 修饰符进行匹配
  13. match_result2 = re.findall(pattern, unicode_str)
  14. print("不使用 re.U 修饰符的匹配结果:", match_result2)
复制代码

3.元字符

3-1 字符匹配元字符

元字符寄义.匹配任意一个字符(换行符除外)^匹配字符串的开头$匹配字符串的末了
  1. import re
  2. # 使用 . 匹配任意字符
  3. string = "abc123"
  4. pattern = r"a.c"
  5. match_object = re.search(pattern, string)
  6. print(match_object.group())  # 输出结果为 "abc"
  7. # 使用 ^ 匹配字符串开头
  8. string = "hello, world!"
  9. pattern = r"^hello"
  10. match_object = re.search(pattern, string)
  11. print(match_object.group())  # 输出结果为 "hello"
  12. # 使用 $ 匹配字符串结尾
  13. string = "hello, world!"
  14. pattern = r"world!$"
  15. match_object = re.search(pattern, string)
  16. print(match_object.group())  # 输出结果为 "world!"
复制代码

3-2 重复次数限定元字符

元字符寄义*匹配前面的字符出现 0 次或多次+匹配前面的字符出现 1 次或多次?匹配前面的字符出现 0 次或 1 次{m}匹配前面的字符恰好出现 m 次{m,}匹配前面的字符至少出现 m 次{m,n}匹配前面的字符出现 m~n 次
  1. import re
  2. # 使用 * 匹配前面的字符出现 0 次或多次
  3. string = "goood job"
  4. pattern = r"go*d"
  5. match_object = re.search(pattern, string)
  6. print(match_object.group())  # 输出结果为 "goood"
  7. # 使用 + 匹配前面的字符出现 1 次或多次
  8. string = "good job"
  9. pattern = r"go+d"
  10. match_object = re.search(pattern, string)
  11. print(match_object.group())  # 输出结果为 "good"
  12. # 使用 ? 匹配前面的字符出现 0 次或 1 次
  13. string1 = "color"
  14. string2 = "colour"
  15. pattern = r"colou?r"
  16. match_object1 = re.search(pattern, string1)
  17. match_object2 = re.search(pattern, string2)
  18. print(match_object1.group())  # 输出结果为 "color"
  19. print(match_object2.group())  # 输出结果为 "colour"
  20. # 使用 {} 匹配前面的字符出现固定次数
  21. string = "12345"
  22. pattern = r"\d{3}"
  23. match_object = re.search(pattern, string)
  24. print(match_object.group())  # 输出结果为 "123"
  25. # 使用 {} 匹配前面的字符出现一定范围内的次数
  26. string = "oooo"
  27. pattern = r"o{2,3}"
  28. match_object = re.search(pattern, string)
  29. print(match_object.group())  # 输出结果为 "oo"
复制代码

3-3 字符聚集匹配元字符

元字符寄义示例[]匹配方括号内的任意一个字符[abc]d 可以匹配 “ad”、“bd”、“cd”,但不能匹配 “dd”[^]匹配不在方括号内的任意一个字符[^abc]d 可以匹配 “dd”、“ed”,但不能匹配 “ad”、“bd”、“cd”
  1. import re
  2. # 使用 [] 匹配方括号内的任意一个字符
  3. string = "abcd"
  4. pattern = r"[abc]d"
  5. match_object = re.search(pattern, string)
  6. print(match_object.group())  # 输出结果为 "cd"
  7. # 使用 [^] 匹配不在方括号内的任意一个字符
  8. string = "abd"
  9. pattern = r"[^afc]d"
  10. match_object = re.search(pattern, string)
  11. print(match_object.group())  # 输出结果为 "bd"
复制代码

3-4 分组元字符

元字符寄义示例()分组,匹配括号内的表达式(go)+ 可以匹配 “gogo”、“gogogo” 等字符串
  1. import re
  2. # 使用 () 进行分组
  3. string = "abc123"
  4. pattern = r"(abc)\d+"
  5. match_object = re.search(pattern, string)
  6. print(match_object.group(1))  # 输出结果为 "abc"
  7. # 使用 (?P<name>) 对捕获的分组进行命名
  8. string = "2023-05-11"
  9. pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
  10. match_object = re.search(pattern, string)
  11. print(match_object.group("year"))  # 输出结果为 "2023"
  12. print(match_object.group("month"))  # 输出结果为 "05"
  13. print(match_object.group("day"))  # 输出结果为 "11"
复制代码

3-5 边界匹配元字符

元字符寄义示例\b匹配单词边界(空格、标点符号等)\bh\w*\b 可以匹配 “hello”、“hi” 等以字母 h 开头的单词\B匹配非单词边界\Bh\w*\B 可以匹配 “ahem”、“shah” 等以字母 h 开头的非单词字符串
  1. import re
  2. # 使用 \b 匹配单词边界
  3. string = "hello, world! hello"
  4. pattern = r"\bhello\b"
  5. match_object = re.findall(pattern, string)
  6. print(match_object)  # 输出结果为 ["hello", "hello"]
  7. # 使用 ^ 匹配字符串开头
  8. string = "hello, world!"
  9. pattern = r"^hello"
  10. match_object = re.findall(pattern, string)
  11. print(match_object)  # 输出结果为 ["hello"]
  12. # 使用 $ 匹配字符串结尾
  13. string = "hello, world"
  14. pattern = r"world$"
  15. match_object = re.findall(pattern, string)
  16. print(match_object)  # 输出结果为 ["world"]
复制代码

3-6 字符类别匹配元字符

元字符寄义示例\d匹配数字\d{3} 可以匹配 “123”,但不能匹配 “1a3”\D匹配非数字字符\D{3} 可以匹配 “abc”,但不能匹配 “a1c”\s匹配任意空缺字符(包括空格、制表符、换行符等)hello\sworld 可以匹配 “hello world” 等包含空缺符的字符串\S匹配任意非空缺字符hello\Sworld 可以匹配 “hello,world” 等不包含空缺符的字符串\w匹配任意字母、数字或下划线\w+ 可以匹配 “hello123”、“world_2021” 等包含字母、数字和下划线的字符串\W匹配任意非字母、数字或下划线字符\W+ 可以匹配 “,!$” 等不包含字母、数字和下划线的字符串
  1. import re
  2. # 使用 \d 匹配数字字符
  3. string = "abc123"
  4. pattern = r"\d+"
  5. match_object = re.search(pattern, string)
  6. print(match_object.group())  # 输出结果为 "123"
  7. # 使用 \w 匹配字母、数字和下划线字符
  8. string = "hello_world_123"
  9. pattern = r"\w+"
  10. match_object = re.findall(pattern, string)
  11. print(match_object)  # 输出结果为 ["hello_world_123"]
  12. # 使用 \s 匹配空白字符
  13. string = "hello world"
  14. pattern = r"\S+"
  15. match_object = re.findall(pattern, string)
  16. print(match_object)  # 输出结果为 ["hello", "world"]
复制代码

4.技巧

4-1 贪婪与非贪婪

*、+ 和 ? 这几个操纵符是贪婪匹配的,它们会只管匹配更多的文本。为了制止贪婪匹配,可以使用 *?、+? 和 ?? 这几个操纵符,它们会只管匹配更少的文本。
  1. import re
  2. # 贪婪匹配示例,输出结果为 "abcccccc"
  3. string = "abcccccc"
  4. pattern = r"abc+"
  5. match_object = re.search(pattern, string)
  6. print(match_object.group())
  7. # 非贪婪匹配示例,输出结果为 "abc"
  8. string = "abcccccc"
  9. pattern = r"abc+?"
  10. match_object = re.search(pattern, string)
  11. print(match_object.group())
复制代码

5.案例

  1. import re
  2. # 电话号码匹配示例,输出结果为 "13812345678"
  3. string = "我的电话是13812345678,请给我打电话。"
  4. pattern = r"1[3456789]\d{9}"
  5. match_object = re.search(pattern, string)
  6. print(match_object.group())
  7. # 邮件地址匹配示例,输出结果为 "example@example.com"
  8. string = "我的邮箱是example@example.com,请发邮件给我。"
  9. pattern = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}"
  10. match_object = re.search(pattern, string, re.IGNORECASE)
  11. print(match_object.group())
  12. # HTML 标签替换示例
  13. string = "<p>我是一段HTML文本。</p>"
  14. pattern = r"<.*?>"
  15. replacement = ""
  16. new_string = re.sub(pattern, replacement, string)
  17. print(new_string)  # 输出结果为 "我是一段HTML文本。"
  18. # 元音字母相邻去重示例,输出结果为 "abbccdddeiouxwxz"
  19. string = "aabbccdddeeiioouuxwxzz"
  20. pattern = r"(a|e|i|o|u|x|w|z)\1+"
  21. match_iter = re.finditer(pattern, string)
  22. for match_object in match_iter:
  23.     old_str = match_object.group()
  24.     new_str = match_object.group(1)
  25.     string = string.replace(old_str, new_str)
  26. print(string)
复制代码

  1. import re
  2. # (hello) 表示创建一个捕获组,输出结果为 "hello"。
  3. string = "hello, world!"
  4. pattern = r"(hello)"
  5. match_object = re.search(pattern, string)
  6. print(match_object.group(1))
  7. # (\d{4})-(\d{2})-(\d{2}) 创建三个捕获组分别用于匹配年、月和日,输出结果为 "2023", "05" 和"11"。
  8. string = "今天是2023-05-11,天气晴朗。"
  9. pattern = r"(\d{4})-(\d{2})-(\d{2})"
  10. match_object = re.search(pattern, string)
  11. print(match_object.group(1))
  12. print(match_object.group(2))
  13. print(match_object.group(3))
  14. # (ab)\1 匹配由两个 "ab" 组成的字符串,输出结果为 "abab"。
  15. string = "ababab"
  16. pattern = r"(ab)\1"
  17. match_object = re.search(pattern, string)
  18. print(match_object.group())
  19. # (ab)(cd)\2\1 匹配由 "abcdcdab"组成的字符串,输出结果为 "abcdcdab"。
  20. string = "abcdcdab"
  21. pattern = r"(ab)(cd)\2\1"
  22. match_object = re.search(pattern, string)
  23. print(match_object.group())
复制代码

圆括号用于创建一个捕获组,以便在后续的表达式中引用。其中,捕获组可以使用 “\1”、“\2” 等符号在表达式中引用到。比方,“(ab)\1” 匹配由两个 “ab” 构成的字符串,而 “(ab)(cd)\2\1” 则匹配由"abcdcdab"构成的字符串。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

写过一篇

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表