活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

正则表达式文本处理的强大利器从基础入门到高级技巧全面解析助你轻松应对各种文本处理挑战提高工作效率成为数据处理高手

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-6 22:10:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

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

x
引言

在当今数据爆炸的时代,文本处理已成为日常工作中不可或缺的一部分。无论是数据分析、日志处理、信息提取还是数据验证,我们经常需要从大量文本中快速准确地找到所需信息。正则表达式(Regular Expression,简称regex或regexp)就是这样一种强大而灵活的文本处理工具,它能够帮助我们以简洁的方式描述和匹配复杂的文本模式,从而极大地提高工作效率。

正则表达式最初由数学家斯蒂芬·科尔·克莱尼(Stephen Cole Kleene)在1950年代提出,后来被广泛应用于计算机科学领域。如今,几乎所有主流编程语言都支持正则表达式,使其成为程序员和数据分析师必备的技能之一。

本文将从正则表达式的基础概念讲起,逐步深入到高级技巧,通过丰富的实例和详细的代码演示,帮助读者全面掌握正则表达式,轻松应对各种文本处理挑战,提高工作效率,成为数据处理高手。

正则表达式基础

什么是正则表达式

正则表达式是一种用于描述字符串模式的强大工具,它由一系列特殊字符和普通字符组成,可以用来检查一个字符串是否含有某种子串、将匹配的子串替换或者从某个字符串中取出符合某个条件的子串等。

简单来说,正则表达式就像是一种”迷你语言”,专门用来处理文本。通过这种语言,我们可以告诉计算机我们想要查找什么样的文本,而不需要明确指定具体的文本内容。

基本语法和元字符

正则表达式的基本语法由普通字符和元字符组成。普通字符(如字母、数字、汉字等)会匹配自身,而元字符则具有特殊的含义。

以下是一些常用的元字符及其含义:

• .:匹配除换行符以外的任意单个字符
• *:匹配前面的子表达式零次或多次
• +:匹配前面的子表达式一次或多次
• ?:匹配前面的子表达式零次或一次
• ^:匹配字符串的开始位置
• $:匹配字符串的结束位置
• \:转义字符,用于匹配特殊字符本身
• |:选择符,匹配”|“左右任意一个表达式
• ():分组,将括号内的表达式作为一个整体
• []:字符类,匹配方括号中的任意一个字符

让我们通过一些简单的例子来理解这些元字符的使用:
  1. import re
  2. # 匹配以"hello"开头的字符串
  3. pattern = r"^hello"
  4. text = "hello world"
  5. print(re.match(pattern, text))  # 输出: <re.Match object; span=(0, 5), match='hello'>
  6. # 匹配以"world"结尾的字符串
  7. pattern = r"world$"
  8. text = "hello world"
  9. print(re.search(pattern, text))  # 输出: <re.Match object; span=(6, 11), match='world'>
  10. # 匹配包含"l"的字符串
  11. pattern = r"l"
  12. text = "hello world"
  13. print(re.findall(pattern, text))  # 输出: ['l', 'l', 'l']
  14. # 匹配"hello"或"world"
  15. pattern = r"hello|world"
  16. text = "hello world"
  17. print(re.findall(pattern, text))  # 输出: ['hello', 'world']
复制代码

字符类和预定义字符集

字符类允许我们匹配一组字符中的任意一个。字符类使用方括号[]表示,例如[abc]可以匹配”a”、”b”或”c”中的任意一个字符。

在字符类中,还可以使用连字符-表示范围,例如[a-z]表示任意小写字母,[0-9]表示任意数字。

此外,正则表达式还提供了一些预定义的字符集,方便我们使用:

• \d:匹配任意数字,相当于[0-9]
• \D:匹配任意非数字字符,相当于[^0-9]
• \w:匹配任意单词字符,包括字母、数字和下划线,相当于[a-zA-Z0-9_]
• \W:匹配任意非单词字符,相当于[^a-zA-Z0-9_]
• \s:匹配任意空白字符,包括空格、制表符、换行符等
• \S:匹配任意非空白字符

让我们看一些例子:
  1. import re
  2. # 匹配任意数字
  3. pattern = r"\d"
  4. text = "hello 123 world"
  5. print(re.findall(pattern, text))  # 输出: ['1', '2', '3']
  6. # 匹配任意单词字符
  7. pattern = r"\w"
  8. text = "hello_world 123"
  9. print(re.findall(pattern, text))  # 输出: ['h', 'e', 'l', 'l', 'o', '_', 'w', 'o', 'r', 'l', 'd', '1', '2', '3']
  10. # 匹配任意空白字符
  11. pattern = r"\s"
  12. text = "hello world"
  13. print(re.findall(pattern, text))  # 输出: [' ']
  14. # 匹配元音字母
  15. pattern = r"[aeiou]"
  16. text = "hello world"
  17. print(re.findall(pattern, text))  # 输出: ['e', 'o', 'o']
  18. # 匹配非元音字母
  19. pattern = r"[^aeiou]"
  20. text = "hello world"
  21. print(re.findall(pattern, text))  # 输出: ['h', 'l', 'l', ' ', 'w', 'r', 'l', 'd']
复制代码

量词

量词用于指定前面的字符或表达式出现的次数。常用的量词有:

• *:匹配前面的子表达式零次或多次
• +:匹配前面的子表达式一次或多次
• ?:匹配前面的子表达式零次或一次
• {n}:匹配前面的子表达式恰好n次
• {n,}:匹配前面的子表达式至少n次
• {n,m}:匹配前面的子表达式至少n次,至多m次

让我们通过一些例子来理解量词的使用:
  1. import re
  2. # 匹配0个或多个数字
  3. pattern = r"\d*"
  4. text = "abc123def"
  5. print(re.findall(pattern, text))  # 输出: ['', '', '', '123', '', '', '']
  6. # 匹配1个或多个数字
  7. pattern = r"\d+"
  8. text = "abc123def"
  9. print(re.findall(pattern, text))  # 输出: ['123']
  10. # 匹配0个或1个数字
  11. pattern = r"\d?"
  12. text = "abc123def"
  13. print(re.findall(pattern, text))  # 输出: ['', '', '', '1', '2', '3', '', '', '']
  14. # 匹配恰好3个数字
  15. pattern = r"\d{3}"
  16. text = "abc123def4567"
  17. print(re.findall(pattern, text))  # 输出: ['123', '456']
  18. # 匹配至少2个数字
  19. pattern = r"\d{2,}"
  20. text = "abc123def4567"
  21. print(re.findall(pattern, text))  # 输出: ['123', '4567']
  22. # 匹配2到4个数字
  23. pattern = r"\d{2,4}"
  24. text = "abc123def4567"
  25. print(re.findall(pattern, text))  # 输出: ['123', '4567']
复制代码

边界匹配

边界匹配用于指定匹配的位置,而不是匹配具体的字符。常用的边界匹配符有:

• ^:匹配字符串的开始位置
• $:匹配字符串的结束位置
• \b:匹配单词边界
• \B:匹配非单词边界

让我们看一些例子:
  1. import re
  2. # 匹配以"hello"开头的字符串
  3. pattern = r"^hello"
  4. text = "hello world"
  5. print(re.findall(pattern, text))  # 输出: ['hello']
  6. # 匹配以"world"结尾的字符串
  7. pattern = r"world$"
  8. text = "hello world"
  9. print(re.findall(pattern, text))  # 输出: ['world']
  10. # 匹配单词"world"
  11. pattern = r"\bworld\b"
  12. text = "hello world"
  13. print(re.findall(pattern, text))  # 输出: ['world']
  14. # 匹配包含"world"但不作为单词的字符串
  15. pattern = r"\Bworld\B"
  16. text = "helloworldhello"
  17. print(re.findall(pattern, text))  # 输出: ['world']
复制代码

正则表达式进阶

分组和捕获

分组是正则表达式中非常重要的概念,它允许我们将多个字符或表达式作为一个整体来处理。分组使用圆括号()表示。

分组不仅可以用于应用量词,还可以用于捕获匹配的内容。当我们使用分组时,正则表达式引擎会”记住”分组匹配的内容,以便后续使用。

让我们看一些例子:
  1. import re
  2. # 匹配连续出现的相同单词
  3. pattern = r"(\w+)\s+\1"
  4. text = "hello hello world"
  5. print(re.findall(pattern, text))  # 输出: ['hello']
  6. # 提取日期中的年、月、日
  7. pattern = r"(\d{4})-(\d{2})-(\d{2})"
  8. text = "Today is 2023-07-15."
  9. match = re.search(pattern, text)
  10. if match:
  11.     print("Year:", match.group(1))  # 输出: Year: 2023
  12.     print("Month:", match.group(2))  # 输出: Month: 07
  13.     print("Day:", match.group(3))  # 输出: Day: 15
  14.     print("Full match:", match.group(0))  # 输出: Full match: 2023-07-15
  15. # 使用命名分组
  16. pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
  17. text = "Today is 2023-07-15."
  18. match = re.search(pattern, text)
  19. if match:
  20.     print("Year:", match.group("year"))  # 输出: Year: 2023
  21.     print("Month:", match.group("month"))  # 输出: Month: 07
  22.     print("Day:", match.group("day"))  # 输出: Day: 15
复制代码

反向引用

反向引用是指引用前面捕获组匹配的内容。在正则表达式中,我们可以使用\1、\2等来引用第一个、第二个捕获组匹配的内容。

反向引用常用于查找重复的单词或模式。让我们看一些例子:
  1. import re
  2. # 查找重复的单词
  3. pattern = r"\b(\w+)\s+\1\b"
  4. text = "hello hello world world"
  5. print(re.findall(pattern, text))  # 输出: ['hello', 'world']
  6. # 查找重复的数字
  7. pattern = r"(\d+)\s+\1"
  8. text = "123 123 456 456"
  9. print(re.findall(pattern, text))  # 输出: ['123', '456']
  10. # 查找HTML标签对
  11. pattern = r"<(\w+)>.+?</\1>"
  12. text = "<div>Hello</div> <span>World</span>"
  13. print(re.findall(pattern, text))  # 输出: ['div', 'span']
复制代码

非捕获组

有时候,我们使用分组只是为了应用量词或者构建复杂的模式,而不需要捕获匹配的内容。这时,我们可以使用非捕获组(?:...)来避免不必要的捕获,提高正则表达式的效率。

让我们看一些例子:
  1. import re
  2. # 使用捕获组
  3. pattern = r"(hello|world)+"
  4. text = "hellohelloworld"
  5. match = re.search(pattern, text)
  6. if match:
  7.     print("Groups:", match.groups())  # 输出: Groups: ('world',)
  8. # 使用非捕获组
  9. pattern = r"(?:hello|world)+"
  10. text = "hellohelloworld"
  11. match = re.search(pattern, text)
  12. if match:
  13.     print("Groups:", match.groups())  # 输出: Groups: ()
  14. # 提取IP地址
  15. pattern = r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
  16. text = "Server IP is 192.168.1.1."
  17. print(re.findall(pattern, text))  # 输出: ['192.168.1.1']
复制代码

零宽断言

零宽断言是一种特殊的匹配,它匹配的是位置而不是字符。零宽断言不会消耗字符,也就是说,它只是检查某个位置是否满足条件,但不会将该位置的字符包含在匹配结果中。

常用的零宽断言有:

• (?=...):正向先行断言,表示后面的位置必须匹配...
• (?!...):负向先行断言,表示后面的位置不能匹配...
• (?<=...):正向后行断言,表示前面的位置必须匹配...
• (?<!...):负向后行断言,表示前面的位置不能匹配...

让我们看一些例子:
  1. import re
  2. # 正向先行断言:匹配后面跟着"world"的"hello"
  3. pattern = r"hello(?=\sworld)"
  4. text = "hello world, hello there"
  5. print(re.findall(pattern, text))  # 输出: ['hello']
  6. # 负向先行断言:匹配后面不跟着"world"的"hello"
  7. pattern = r"hello(?!\sworld)"
  8. text = "hello world, hello there"
  9. print(re.findall(pattern, text))  # 输出: ['hello']
  10. # 正向后行断言:匹配前面是"hello"的"world"
  11. pattern = r"(?<=hello\s)world"
  12. text = "hello world, hi world"
  13. print(re.findall(pattern, text))  # 输出: ['world']
  14. # 负向后行断言:匹配前面不是"hello"的"world"
  15. pattern = r"(?<!hello\s)world"
  16. text = "hello world, hi world"
  17. print(re.findall(pattern, text))  # 输出: ['world']
  18. # 提取金额数字
  19. pattern = r"(?<=\$)\d+"
  20. text = "Price: $100, $200, $300"
  21. print(re.findall(pattern, text))  # 输出: ['100', '200', '300']
复制代码

贪婪与非贪婪匹配

默认情况下,正则表达式的量词是”贪婪”的,这意味着它们会尽可能多地匹配字符。例如,表达式a.*b会匹配从第一个”a”到最后一个”b”之间的所有字符,而不是到第一个”b”就停止。

有时候,我们可能需要”非贪婪”匹配,即尽可能少地匹配字符。在量词后面加上?可以使其变为非贪婪模式。

让我们看一些例子:
  1. import re
  2. # 贪婪匹配
  3. pattern = r"a.*b"
  4. text = "aabab"
  5. print(re.findall(pattern, text))  # 输出: ['aabab']
  6. # 非贪婪匹配
  7. pattern = r"a.*?b"
  8. text = "aabab"
  9. print(re.findall(pattern, text))  # 输出: ['aab', 'ab']
  10. # 贪婪匹配HTML标签内容
  11. pattern = r"<div>.*</div>"
  12. text = "<div>Hello</div><div>World</div>"
  13. print(re.findall(pattern, text))  # 输出: ['<div>Hello</div><div>World</div>']
  14. # 非贪婪匹配HTML标签内容
  15. pattern = r"<div>.*?</div>"
  16. text = "<div>Hello</div><div>World</div>"
  17. print(re.findall(pattern, text))  # 输出: ['<div>Hello</div>', '<div>World</div>']
  18. # 贪婪匹配引号内的内容
  19. pattern = r"'.*'"
  20. text = "'Hello', 'World'"
  21. print(re.findall(pattern, text))  # 输出: ["'Hello', 'World'"]
  22. # 非贪婪匹配引号内的内容
  23. pattern = r"'.*?'"
  24. text = "'Hello', 'World'"
  25. print(re.findall(pattern, text))  # 输出: ["'Hello'", "'World'"]
复制代码

正则表达式高级技巧

回溯控制

回溯是正则表达式引擎在匹配过程中的一种机制,当一条路径匹配失败时,引擎会回退到上一个决策点,尝试其他可能的匹配路径。虽然回溯使得正则表达式更加灵活,但过多的回溯会导致性能下降,甚至造成”灾难性回溯”(Catastrophic Backtracking)。

为了避免过多的回溯,我们可以使用原子组(?>...)和占有量词?+、*+、++、{n,m}+来限制回溯。

让我们看一些例子:
  1. import re
  2. # 普通分组(可能导致灾难性回溯)
  3. pattern = r"(\d+)+"
  4. text = "1234567890"
  5. print(re.findall(pattern, text))  # 输出: ['1234567890']
  6. # 原子组(限制回溯)
  7. pattern = r"(?>\d+)+"
  8. text = "1234567890"
  9. print(re.findall(pattern, text))  # 输出: ['1234567890']
  10. # 占有量词(限制回溯)
  11. pattern = r"\d++"
  12. text = "1234567890"
  13. print(re.findall(pattern, text))  # 输出: ['1234567890']
  14. # 避免灾难性回溯的例子
  15. # 这个正则表达式在匹配不成功的嵌套括号时会导致灾难性回溯
  16. pattern = r"\(((?>[^()]+|(?R))*)\)"
  17. text = "(" + "a" * 30  # 嵌套很深的字符串
  18. try:
  19.     re.search(pattern, text)
  20. except re.error:
  21.     print("Regex error occurred")  # 可能会输出这个错误
  22. # 优化后的正则表达式,避免灾难性回溯
  23. pattern = r"\(([^()]*)\)"
  24. text = "(" + "a" * 30
  25. try:
  26.     re.search(pattern, text)
  27.     print("No error occurred")  # 会输出这个
  28. except re.error:
  29.     print("Regex error occurred")
复制代码

条件匹配

条件匹配允许我们根据某个条件是否满足来决定匹配的模式。条件匹配的语法为(?(condition)yes-pattern|no-pattern),其中condition可以是一个捕获组的编号或名称,也可以是一个断言。

让我们看一些例子:
  1. import re
  2. # 如果有捕获组1,则匹配"yes",否则匹配"no"
  3. pattern = r"(\d)?(?(1)yes|no)"
  4. text1 = "123yes"
  5. text2 = "abcno"
  6. print(re.findall(pattern, text1))  # 输出: ['1', 'yes']
  7. print(re.findall(pattern, text2))  # 输出: ['', 'no']
  8. # 如果前面有"hello",则匹配"world",否则匹配"there"
  9. pattern = r"(hello)?(?(1)world|there)"
  10. text1 = "helloworld"
  11. text2 = "hi there"
  12. print(re.findall(pattern, text1))  # 输出: ['hello', 'world']
  13. print(re.findall(pattern, text2))  # 输出: ['', 'there']
  14. # 使用命名条件
  15. pattern = r"(?P<word>hello)?(?(word)world|there)"
  16. text1 = "helloworld"
  17. text2 = "hi there"
  18. print(re.findall(pattern, text1))  # 输出: ['hello', 'world']
  19. print(re.findall(pattern, text2))  # 输出: ['', 'there']
复制代码

正则表达式优化

正则表达式虽然强大,但如果不注意优化,可能会导致性能问题。以下是一些优化正则表达式的技巧:

1. 避免不必要的捕获:使用非捕获组(?:...)代替捕获组(...),除非确实需要捕获匹配的内容。
2. 使用具体的字符类:使用具体的字符类如[0-9]代替通用的\d,使用[a-zA-Z0-9_]代替\w,这样可以提高匹配速度。
3. 避免贪婪匹配:在可能的情况下,使用非贪婪匹配*?、+?、??、{n,m}?代替贪婪匹配,以减少回溯。
4. 使用原子组和占有量词:使用原子组(?>...)和占有量词?+、*+、++、{n,m}+来限制回溯,提高性能。
5. 避免嵌套量词:避免使用嵌套的量词,如(a+)+,这可能导致灾难性回溯。
6. 使用锚点:使用^和$锚点来限制匹配的位置,减少不必要的尝试。
7. 预编译正则表达式:在Python中,可以使用re.compile()预编译正则表达式,提高重复使用的效率。

避免不必要的捕获:使用非捕获组(?:...)代替捕获组(...),除非确实需要捕获匹配的内容。

使用具体的字符类:使用具体的字符类如[0-9]代替通用的\d,使用[a-zA-Z0-9_]代替\w,这样可以提高匹配速度。

避免贪婪匹配:在可能的情况下,使用非贪婪匹配*?、+?、??、{n,m}?代替贪婪匹配,以减少回溯。

使用原子组和占有量词:使用原子组(?>...)和占有量词?+、*+、++、{n,m}+来限制回溯,提高性能。

避免嵌套量词:避免使用嵌套的量词,如(a+)+,这可能导致灾难性回溯。

使用锚点:使用^和$锚点来限制匹配的位置,减少不必要的尝试。

预编译正则表达式:在Python中,可以使用re.compile()预编译正则表达式,提高重复使用的效率。

让我们看一些优化的例子:
  1. import re
  2. import time
  3. # 未优化的正则表达式
  4. pattern1 = r".*(\d+).*"
  5. text = "a" * 1000000 + "12345" + "b" * 1000000
  6. # 优化的正则表达式
  7. pattern2 = r".*?(\d+).*"
  8. # 测试未优化的正则表达式
  9. start_time = time.time()
  10. re.search(pattern1, text)
  11. end_time = time.time()
  12. print("Unoptimized regex time:", end_time - start_time)
  13. # 测试优化的正则表达式
  14. start_time = time.time()
  15. re.search(pattern2, text)
  16. end_time = time.time()
  17. print("Optimized regex time:", end_time - start_time)
  18. # 预编译正则表达式
  19. compiled_pattern = re.compile(pattern2)
  20. start_time = time.time()
  21. compiled_pattern.search(text)
  22. end_time = time.time()
  23. print("Precompiled regex time:", end_time - start_time)
复制代码

常见正则表达式模式

在实际应用中,有一些常见的正则表达式模式被广泛使用。下面列出了一些常见的模式及其用途:

1.
  1. 电子邮件地址:pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
  2. email = "example@example.com"
  3. print(re.match(pattern, email))  # 输出: <re.Match object; span=(0, 19), match='example@example.com'>
复制代码
2.
  1. URL:pattern = r"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+"
  2. url = "https://www.example.com"
  3. print(re.match(pattern, url))  # 输出: <re.Match object; span=(0, 23), match='https://www.example.com'>
复制代码
3.
  1. IP地址:pattern = r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
  2. ip = "192.168.1.1"
  3. print(re.match(pattern, ip))  # 输出: <re.Match object; span=(0, 11), match='192.168.1.1'>
复制代码
4.
  1. 日期(YYYY-MM-DD):pattern = r"\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])"
  2. date = "2023-07-15"
  3. print(re.match(pattern, date))  # 输出: <re.Match object; span=(0, 10), match='2023-07-15'>
复制代码
5.
  1. 时间(HH:MM:SS):pattern = r"([01]\d|2[0-3]):([0-5]\d):([0-5]\d)"
  2. time_str = "23:59:59"
  3. print(re.match(pattern, time_str))  # 输出: <re.Match object; span=(0, 8), match='23:59:59'>
复制代码
6.
  1. HTML标签:pattern = r"<([a-z]+)(?:\s+[^>]*)?>.*?</\1>"
  2. html = "<div class='example'>Hello</div>"
  3. print(re.match(pattern, html))  # 输出: <re.Match object; span=(0, 31), match='<div class='example'>Hello</div>'>
复制代码
7.
  1. 中文字符:pattern = r"[\u4e00-\u9fa5]+"
  2. chinese = "你好,世界"
  3. print(re.findall(pattern, chinese))  # 输出: ['你好', '世界']
复制代码
8.
  1. 手机号码:pattern = r"1[3-9]\d{9}"
  2. phone = "13800138000"
  3. print(re.match(pattern, phone))  # 输出: <re.Match object; span=(0, 11), match='13800138000'>
复制代码
9.
  1. 身份证号码:pattern = r"[1-9]\d{5}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]"
  2. id_card = "11010519491231002X"
  3. print(re.match(pattern, id_card))  # 输出: <re.Match object; span=(0, 18), match='11010519491231002X'>
复制代码
10.
  1. 密码强度(至少8个字符,包含大小写字母、数字和特殊字符):pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
  2. password = "Password123!"
  3. print(re.match(pattern, password))  # 输出: <re.Match object; span=(0, 12), match='Password123!'>
复制代码

电子邮件地址:
  1. pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
  2. email = "example@example.com"
  3. print(re.match(pattern, email))  # 输出: <re.Match object; span=(0, 19), match='example@example.com'>
复制代码

URL:
  1. pattern = r"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+"
  2. url = "https://www.example.com"
  3. print(re.match(pattern, url))  # 输出: <re.Match object; span=(0, 23), match='https://www.example.com'>
复制代码

IP地址:
  1. pattern = r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
  2. ip = "192.168.1.1"
  3. print(re.match(pattern, ip))  # 输出: <re.Match object; span=(0, 11), match='192.168.1.1'>
复制代码

日期(YYYY-MM-DD):
  1. pattern = r"\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])"
  2. date = "2023-07-15"
  3. print(re.match(pattern, date))  # 输出: <re.Match object; span=(0, 10), match='2023-07-15'>
复制代码

时间(HH:MM:SS):
  1. pattern = r"([01]\d|2[0-3]):([0-5]\d):([0-5]\d)"
  2. time_str = "23:59:59"
  3. print(re.match(pattern, time_str))  # 输出: <re.Match object; span=(0, 8), match='23:59:59'>
复制代码

HTML标签:
  1. pattern = r"<([a-z]+)(?:\s+[^>]*)?>.*?</\1>"
  2. html = "<div class='example'>Hello</div>"
  3. print(re.match(pattern, html))  # 输出: <re.Match object; span=(0, 31), match='<div class='example'>Hello</div>'>
复制代码

中文字符:
  1. pattern = r"[\u4e00-\u9fa5]+"
  2. chinese = "你好,世界"
  3. print(re.findall(pattern, chinese))  # 输出: ['你好', '世界']
复制代码

手机号码:
  1. pattern = r"1[3-9]\d{9}"
  2. phone = "13800138000"
  3. print(re.match(pattern, phone))  # 输出: <re.Match object; span=(0, 11), match='13800138000'>
复制代码

身份证号码:
  1. pattern = r"[1-9]\d{5}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]"
  2. id_card = "11010519491231002X"
  3. print(re.match(pattern, id_card))  # 输出: <re.Match object; span=(0, 18), match='11010519491231002X'>
复制代码

密码强度(至少8个字符,包含大小写字母、数字和特殊字符):
  1. pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
  2. password = "Password123!"
  3. print(re.match(pattern, password))  # 输出: <re.Match object; span=(0, 12), match='Password123!'>
复制代码

正则表达式在不同编程语言中的应用

Python中的正则表达式

Python提供了re模块来支持正则表达式操作。re模块中常用的函数有:

• re.match(pattern, string):从字符串的起始位置匹配一个模式,如果匹配成功,返回一个匹配对象;否则返回None。
• re.search(pattern, string):扫描整个字符串,返回第一个成功的匹配对象;如果没有匹配,则返回None。
• re.findall(pattern, string):查找字符串中所有匹配的子串,并返回一个列表。
• re.finditer(pattern, string):查找字符串中所有匹配的子串,并返回一个迭代器。
• re.sub(pattern, repl, string):替换字符串中所有匹配的子串。
• re.split(pattern, string):根据匹配的子串分割字符串。
• re.compile(pattern):编译正则表达式,返回一个正则表达式对象。

让我们看一些Python中使用正则表达式的例子:
  1. import re
  2. # 编译正则表达式
  3. pattern = re.compile(r"\d+")
  4. # 使用match方法
  5. text = "123abc"
  6. match = pattern.match(text)
  7. if match:
  8.     print("Match found:", match.group())  # 输出: Match found: 123
  9. # 使用search方法
  10. text = "abc123def"
  11. match = pattern.search(text)
  12. if match:
  13.     print("Match found:", match.group())  # 输出: Match found: 123
  14. # 使用findall方法
  15. text = "abc123def456"
  16. matches = pattern.findall(text)
  17. print("All matches:", matches)  # 输出: All matches: ['123', '456']
  18. # 使用sub方法
  19. text = "abc123def456"
  20. new_text = pattern.sub("NUM", text)
  21. print("After substitution:", new_text)  # 输出: After substitution: abcNUMdefNUM
  22. # 使用split方法
  23. text = "abc123def456ghi"
  24. parts = pattern.split(text)
  25. print("After splitting:", parts)  # 输出: After splitting: ['abc', 'def', 'ghi']
  26. # 使用finditer方法
  27. text = "abc123def456ghi"
  28. for match in pattern.finditer(text):
  29.     print("Match found:", match.group(), "at position", match.span())
  30. # 输出:
  31. # Match found: 123 at position (3, 6)
  32. # Match found: 456 at position (9, 12)
复制代码

JavaScript中的正则表达式

在JavaScript中,正则表达式可以通过两种方式创建:字面量形式和构造函数形式。

字面量形式:/pattern/flags构造函数形式:new RegExp(pattern, flags)

常用的标志(flags)有:

• g:全局匹配,查找所有匹配而非在找到第一个匹配后停止
• i:忽略大小写
• m:多行模式,^和$可以匹配每行的开始和结束
• s:让.匹配包括换行符在内的所有字符
• u:Unicode模式
• y:粘性模式,只在目标字符串的当前位置匹配

JavaScript中常用的正则表达式方法有:

• RegExp.prototype.test(string):测试字符串是否匹配正则表达式,返回true或false。
• RegExp.prototype.exec(string):在字符串中执行匹配搜索,返回结果数组或null。
• String.prototype.match(regexp):在字符串中执行匹配搜索,返回结果数组或null。
• String.prototype.search(regexp):在字符串中查找匹配,返回匹配的索引或-1。
• String.prototype.replace(regexp, replacement):替换字符串中匹配的子串。
• String.prototype.split(regexp):根据匹配的子串分割字符串。

让我们看一些JavaScript中使用正则表达式的例子:
  1. // 创建正则表达式
  2. const pattern = /\d+/g;
  3. // 使用test方法
  4. const text1 = "123abc";
  5. console.log(pattern.test(text1));  // 输出: true
  6. // 使用exec方法
  7. const text2 = "abc123def456";
  8. let match;
  9. while ((match = pattern.exec(text2)) !== null) {
  10.     console.log("Match found:", match[0], "at position", match.index);
  11. }
  12. // 输出:
  13. // Match found: 123 at position 3
  14. // Match found: 456 at position 9
  15. // 使用match方法
  16. const text3 = "abc123def456";
  17. const matches = text3.match(pattern);
  18. console.log("All matches:", matches);  // 输出: All matches: ['123', '456']
  19. // 使用search方法
  20. const text4 = "abc123def";
  21. const index = text4.search(pattern);
  22. console.log("Match found at index:", index);  // 输出: Match found at index: 3
  23. // 使用replace方法
  24. const text5 = "abc123def456";
  25. const new_text = text5.replace(pattern, "NUM");
  26. console.log("After substitution:", new_text);  // 输出: After substitution: abcNUMdefNUM
  27. // 使用split方法
  28. const text6 = "abc123def456ghi";
  29. const parts = text6.split(pattern);
  30. console.log("After splitting:", parts);  // 输出: After splitting: ['abc', 'def', 'ghi']
复制代码

Java中的正则表达式

Java提供了java.util.regex包来支持正则表达式操作。该包中主要有两个类:Pattern和Matcher。

Pattern类用于编译正则表达式,常用的方法有:

• Pattern.compile(String regex):编译正则表达式,返回一个Pattern对象。
• Pattern.matches(String regex, CharSequence input):编译给定的正则表达式并尝试匹配输入的字符串。

Matcher类用于执行匹配操作,常用的方法有:

• matcher.matches():尝试将整个区域与模式匹配。
• matcher.lookingAt():尝试将区域开头与模式匹配。
• matcher.find():尝试查找与模式匹配的输入序列的下一个子序列。
• matcher.group():返回上一个匹配匹配的输入子序列。
• matcher.start():返回上一个匹配的开始索引。
• matcher.end():返回上一个匹配的结束索引。
• matcher.replaceAll(String replacement):替换所有匹配的子序列。
• matcher.replaceFirst(String replacement):替换第一个匹配的子序列。

此外,String类也提供了一些使用正则表达式的方法:

• String.matches(String regex):判断字符串是否匹配给定的正则表达式。
• String.split(String regex):根据匹配给定的正则表达式来拆分此字符串。
• String.replaceAll(String regex, String replacement):替换所有匹配的子串。
• String.replaceFirst(String regex, String replacement):替换第一个匹配的子串。

让我们看一些Java中使用正则表达式的例子:
  1. import java.util.regex.*;
  2. public class RegexExample {
  3.     public static void main(String[] args) {
  4.         // 编译正则表达式
  5.         Pattern pattern = Pattern.compile("\\d+");
  6.         
  7.         // 使用matches方法
  8.         String text1 = "123abc";
  9.         Matcher matcher1 = pattern.matcher(text1);
  10.         System.out.println("Matches: " + matcher1.matches());  // 输出: Matches: false
  11.         
  12.         // 使用lookingAt方法
  13.         Matcher matcher2 = pattern.matcher(text1);
  14.         System.out.println("Looking at: " + matcher2.lookingAt());  // 输出: Looking at: true
  15.         
  16.         // 使用find方法
  17.         String text2 = "abc123def456";
  18.         Matcher matcher3 = pattern.matcher(text2);
  19.         while (matcher3.find()) {
  20.             System.out.println("Match found: " + matcher3.group() + " at position " + matcher3.start());
  21.         }
  22.         // 输出:
  23.         // Match found: 123 at position 3
  24.         // Match found: 456 at position 9
  25.         
  26.         // 使用replaceAll方法
  27.         String text3 = "abc123def456";
  28.         String new_text = matcher3.replaceAll("NUM");
  29.         System.out.println("After substitution: " + new_text);  // 输出: After substitution: abcNUMdefNUM
  30.         
  31.         // 使用String的matches方法
  32.         String text4 = "123abc";
  33.         System.out.println("Matches: " + text4.matches("\\d+.*"));  // 输出: Matches: true
  34.         
  35.         // 使用String的split方法
  36.         String text5 = "abc123def456ghi";
  37.         String[] parts = text5.split("\\d+");
  38.         System.out.println("After splitting: " + Arrays.toString(parts));  // 输出: After splitting: [abc, def, ghi]
  39.         
  40.         // 使用String的replaceAll方法
  41.         String text6 = "abc123def456";
  42.         String new_text2 = text6.replaceAll("\\d+", "NUM");
  43.         System.out.println("After substitution: " + new_text2);  // 输出: After substitution: abcNUMdefNUM
  44.     }
  45. }
复制代码

其他语言中的正则表达式

除了Python、JavaScript和Java,其他编程语言也提供了对正则表达式的支持。下面简要介绍一些其他语言中的正则表达式使用方法:

C#提供了System.Text.RegularExpressions命名空间来支持正则表达式操作。主要的类是Regex,常用的方法有:

• Regex.IsMatch(string input, string pattern):判断输入字符串是否匹配正则表达式。
• Regex.Match(string input, string pattern):在输入字符串中搜索正则表达式的第一个匹配项。
• Regex.Matches(string input, string pattern):在输入字符串中搜索正则表达式的所有匹配项。
• Regex.Replace(string input, string pattern, string replacement):替换输入字符串中匹配正则表达式的所有子串。
• Regex.Split(string input, string pattern):根据匹配正则表达式的子串分割输入字符串。
  1. using System;
  2. using System.Text.RegularExpressions;
  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         // 使用IsMatch方法
  8.         string text1 = "123abc";
  9.         Console.WriteLine("Matches: " + Regex.IsMatch(text1, @"\d+"));  // 输出: Matches: True
  10.         
  11.         // 使用Match方法
  12.         string text2 = "abc123def";
  13.         Match match = Regex.Match(text2, @"\d+");
  14.         if (match.Success)
  15.         {
  16.             Console.WriteLine("Match found: " + match.Value + " at position " + match.Index);  // 输出: Match found: 123 at position 3
  17.         }
  18.         
  19.         // 使用Matches方法
  20.         string text3 = "abc123def456";
  21.         MatchCollection matches = Regex.Matches(text3, @"\d+");
  22.         foreach (Match m in matches)
  23.         {
  24.             Console.WriteLine("Match found: " + m.Value + " at position " + m.Index);
  25.         }
  26.         // 输出:
  27.         // Match found: 123 at position 3
  28.         // Match found: 456 at position 9
  29.         
  30.         // 使用Replace方法
  31.         string text4 = "abc123def456";
  32.         string new_text = Regex.Replace(text4, @"\d+", "NUM");
  33.         Console.WriteLine("After substitution: " + new_text);  // 输出: After substitution: abcNUMdefNUM
  34.         
  35.         // 使用Split方法
  36.         string text5 = "abc123def456ghi";
  37.         string[] parts = Regex.Split(text5, @"\d+");
  38.         Console.WriteLine("After splitting: " + string.Join(", ", parts));  // 输出: After splitting: abc, def, ghi
  39.     }
  40. }
复制代码

PHP提供了preg_系列函数来支持正则表达式操作,常用的函数有:

• preg_match(string $pattern, string $subject, array &$matches = null):执行一个正则表达式匹配。
• preg_match_all(string $pattern, string $subject, array &$matches = null):执行一个全局正则表达式匹配。
• preg_replace(string $pattern, string $replacement, string $subject):执行一个正则表达式的搜索和替换。
• preg_split(string $pattern, string $subject):通过一个正则表达式分隔字符串。
  1. <?php
  2. // 使用preg_match函数
  3. $text1 = "123abc";
  4. if (preg_match("/\d+/", $text1, $matches)) {
  5.     echo "Match found: " . $matches[0] . "\n";  // 输出: Match found: 123
  6. }
  7. // 使用preg_match_all函数
  8. $text2 = "abc123def456";
  9. if (preg_match_all("/\d+/", $text2, $matches)) {
  10.     echo "All matches: " . implode(", ", $matches[0]) . "\n";  // 输出: All matches: 123, 456
  11. }
  12. // 使用preg_replace函数
  13. $text3 = "abc123def456";
  14. $new_text = preg_replace("/\d+/", "NUM", $text3);
  15. echo "After substitution: " . $new_text . "\n";  // 输出: After substitution: abcNUMdefNUM
  16. // 使用preg_split函数
  17. $text4 = "abc123def456ghi";
  18. $parts = preg_split("/\d+/", $text4);
  19. echo "After splitting: " . implode(", ", $parts) . "\n";  // 输出: After splitting: abc, def, ghi
  20. ?>
复制代码

Ruby内置了对正则表达式的支持,可以通过/pattern/或Regexp.new(pattern)创建正则表达式对象。常用的方法有:

• Regexp#match(string):在字符串中搜索正则表达式的匹配项。
• String#=~(regexp):在字符串中搜索正则表达式的匹配项,返回匹配的位置或nil。
• String#match(regexp):在字符串中搜索正则表达式的匹配项,返回MatchData对象或nil。
• String#gsub(pattern, replacement):替换字符串中所有匹配的子串。
• String#split(pattern):根据匹配的子串分割字符串。
  1. # 使用match方法
  2. text1 = "123abc"
  3. match_data = /\d+/.match(text1)
  4. puts "Match found: #{match_data[0]}" if match_data  # 输出: Match found: 123
  5. # 使用=~方法
  6. text2 = "abc123def"
  7. position = text2 =~ /\d+/
  8. puts "Match found at position: #{position}" if position  # 输出: Match found at position: 3
  9. # 使用scan方法
  10. text3 = "abc123def456"
  11. matches = text3.scan(/\d+/)
  12. puts "All matches: #{matches.join(', ')}"  # 输出: All matches: 123, 456
  13. # 使用gsub方法
  14. text4 = "abc123def456"
  15. new_text = text4.gsub(/\d+/, "NUM")
  16. puts "After substitution: #{new_text}"  # 输出: After substitution: abcNUMdefNUM
  17. # 使用split方法
  18. text5 = "abc123def456ghi"
  19. parts = text5.split(/\d+/)
  20. puts "After splitting: #{parts.join(', ')}"  # 输出: After splitting: abc, def, ghi
复制代码

Go语言通过regexp包提供对正则表达式的支持。常用的函数有:

• regexp.MustCompile(string) *Regexp:编译正则表达式,返回一个Regexp对象。
• regexp.Compile(string) (*Regexp, error):编译正则表达式,返回一个Regexp对象和可能的错误。
• (*Regexp) MatchString(string) bool:判断字符串是否匹配正则表达式。
• (*Regexp) FindString(string) string:在字符串中查找正则表达式的第一个匹配项。
• (*Regexp) FindAllString(string, int) []string:在字符串中查找正则表达式的所有匹配项。
• (*Regexp) ReplaceAllString(string, string) string:替换字符串中所有匹配的子串。
• (*Regexp) Split(string, int) []string:根据匹配的子串分割字符串。
  1. package main
  2. import (
  3.         "fmt"
  4.         "regexp"
  5. )
  6. func main() {
  7.         // 编译正则表达式
  8.         pattern := regexp.MustCompile(`\d+`)
  9.         // 使用MatchString方法
  10.         text1 := "123abc"
  11.         fmt.Println("Matches:", pattern.MatchString(text1))  // 输出: Matches: true
  12.         // 使用FindString方法
  13.         text2 := "abc123def"
  14.         match := pattern.FindString(text2)
  15.         fmt.Println("Match found:", match)  // 输出: Match found: 123
  16.         // 使用FindAllString方法
  17.         text3 := "abc123def456"
  18.         matches := pattern.FindAllString(text3, -1)
  19.         fmt.Println("All matches:", matches)  // 输出: All matches: [123 456]
  20.         // 使用ReplaceAllString方法
  21.         text4 := "abc123def456"
  22.         new_text := pattern.ReplaceAllString(text4, "NUM")
  23.         fmt.Println("After substitution:", new_text)  // 输出: After substitution: abcNUMdefNUM
  24.         // 使用Split方法
  25.         text5 := "abc123def456ghi"
  26.         parts := pattern.Split(text5, -1)
  27.         fmt.Println("After splitting:", parts)  // 输出: After splitting: [abc def ghi]
  28. }
复制代码

实战案例

数据验证

正则表达式在数据验证中有着广泛的应用,例如验证电子邮件地址、手机号码、身份证号码等。下面是一些常见的数据验证示例:
  1. import re
  2. def validate_email(email):
  3.     pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
  4.     if re.match(pattern, email):
  5.         return True
  6.     else:
  7.         return False
  8. # 测试
  9. emails = [
  10.     "example@example.com",
  11.     "user.name@domain.co.uk",
  12.     "user+tag@domain.com",
  13.     "invalid.email@",
  14.     "@invalid.com",
  15.     "invalid@.com"
  16. ]
  17. for email in emails:
  18.     print(f"{email}: {validate_email(email)}")
复制代码
  1. import re
  2. def validate_phone(phone):
  3.     # 中国手机号码验证
  4.     pattern = r"^1[3-9]\d{9}$"
  5.     if re.match(pattern, phone):
  6.         return True
  7.     else:
  8.         return False
  9. # 测试
  10. phones = [
  11.     "13800138000",
  12.     "15912345678",
  13.     "12345678901",
  14.     "1380013800",
  15.     "138001380000"
  16. ]
  17. for phone in phones:
  18.     print(f"{phone}: {validate_phone(phone)}")
复制代码
  1. import re
  2. def validate_id_card(id_card):
  3.     # 中国身份证号码验证
  4.     pattern = r"^[1-9]\d{5}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$"
  5.     if re.match(pattern, id_card):
  6.         return True
  7.     else:
  8.         return False
  9. # 测试
  10. id_cards = [
  11.     "11010519491231002X",
  12.     "110105194912310021",
  13.     "11010519491331002X",
  14.     "11010519491232002X",
  15.     "11010519491231002"
  16. ]
  17. for id_card in id_cards:
  18.     print(f"{id_card}: {validate_id_card(id_card)}")
复制代码
  1. import re
  2. def validate_password(password):
  3.     # 密码至少8个字符,包含大小写字母、数字和特殊字符
  4.     pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
  5.     if re.match(pattern, password):
  6.         return True
  7.     else:
  8.         return False
  9. # 测试
  10. passwords = [
  11.     "Password123!",
  12.     "password123!",
  13.     "PASSWORD123!",
  14.     "Password123",
  15.     "Pass123!",
  16.     "Password123456!"
  17. ]
  18. for password in passwords:
  19.     print(f"{password}: {validate_password(password)}")
复制代码

文本提取和替换

正则表达式在文本提取和替换中也非常有用,例如从HTML中提取链接、从日志中提取特定信息、批量替换文本等。下面是一些示例:
  1. import re
  2. def extract_links(html):
  3.     pattern = r'<a\s+(?:[^>]*?\s+)?href="([^"]*)"'
  4.     return re.findall(pattern, html)
  5. # 测试
  6. html = """
  7. <html>
  8. <body>
  9. <a href="https://www.example.com">Example</a>
  10. <a href="https://www.google.com">Google</a>
  11. <a href="https://www.github.com">GitHub</a>
  12. </body>
  13. </html>
  14. """
  15. links = extract_links(html)
  16. for link in links:
  17.     print(link)
复制代码
  1. import re
  2. def extract_log_info(log):
  3.     # 提取IP地址
  4.     ip_pattern = r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
  5.     ips = re.findall(ip_pattern, log)
  6.    
  7.     # 提取时间戳
  8.     timestamp_pattern = r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"
  9.     timestamps = re.findall(timestamp_pattern, log)
  10.    
  11.     return ips, timestamps
  12. # 测试
  13. log = """
  14. 192.168.1.1 - - [2023-07-15 10:30:45] "GET /index.html HTTP/1.1" 200 1234
  15. 192.168.1.2 - - [2023-07-15 10:31:12] "POST /login HTTP/1.1" 200 567
  16. 192.168.1.3 - - [2023-07-15 10:32:01] "GET /dashboard HTTP/1.1" 404 89
  17. """
  18. ips, timestamps = extract_log_info(log)
  19. print("IP addresses:", ips)
  20. print("Timestamps:", timestamps)
复制代码
  1. import re
  2. def replace_date_format(text):
  3.     # 将MM/DD/YYYY格式的日期替换为YYYY-MM-DD格式
  4.     pattern = r"\b(\d{2})/(\d{2})/(\d{4})\b"
  5.     replacement = r"\3-\1-\2"
  6.     return re.sub(pattern, replacement, text)
  7. # 测试
  8. text = """
  9. The event will be held on 07/15/2023.
  10. Another event is scheduled for 12/25/2023.
  11. The deadline is 01/01/2024.
  12. """
  13. new_text = replace_date_format(text)
  14. print(new_text)
复制代码
  1. import re
  2. def extract_emails(text):
  3.     pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
  4.     return re.findall(pattern, text)
  5. # 测试
  6. text = """
  7. Contact us at support@example.com for assistance.
  8. You can also reach out to sales@company.com or info@organization.org.
  9. For urgent matters, please contact emergency@service.gov.
  10. """
  11. emails = extract_emails(text)
  12. for email in emails:
  13.     print(email)
复制代码

日志分析

正则表达式在日志分析中非常有用,可以帮助我们从大量的日志数据中提取有用的信息。下面是一些示例:
  1. import re
  2. from collections import Counter
  3. def analyze_web_log(log):
  4.     # 提取IP地址、请求方法、URL和状态码
  5.     pattern = r'(\b(?:\d{1,3}\.){3}\d{1,3}\b).*?"(\w+)\s+([^\s]+)\s+HTTP/1.\d"\s+(\d{3})'
  6.     matches = re.findall(pattern, log)
  7.    
  8.     # 统计IP地址访问次数
  9.     ip_counter = Counter(match[0] for match in matches)
  10.    
  11.     # 统计请求方法
  12.     method_counter = Counter(match[1] for match in matches)
  13.    
  14.     # 统计URL访问次数
  15.     url_counter = Counter(match[2] for match in matches)
  16.    
  17.     # 统计状态码
  18.     status_counter = Counter(match[3] for match in matches)
  19.    
  20.     return {
  21.         "ip_counter": ip_counter,
  22.         "method_counter": method_counter,
  23.         "url_counter": url_counter,
  24.         "status_counter": status_counter
  25.     }
  26. # 测试
  27. log = """
  28. 192.168.1.1 - - [15/Jul/2023:10:30:45 +0800] "GET /index.html HTTP/1.1" 200 1234
  29. 192.168.1.2 - - [15/Jul/2023:10:31:12 +0800] "POST /login HTTP/1.1" 200 567
  30. 192.168.1.3 - - [15/Jul/2023:10:32:01 +0800] "GET /dashboard HTTP/1.1" 404 89
  31. 192.168.1.1 - - [15/Jul/2023:10:33:22 +0800] "GET /profile HTTP/1.1" 200 2345
  32. 192.168.1.2 - - [15/Jul/2023:10:34:05 +0800] "GET /settings HTTP/1.1" 200 1567
  33. 192.168.1.4 - - [15/Jul/2023:10:35:17 +0800] "GET /index.html HTTP/1.1" 200 1234
  34. """
  35. result = analyze_web_log(log)
  36. print("Top IP addresses:")
  37. for ip, count in result["ip_counter"].most_common(3):
  38.     print(f"{ip}: {count}")
  39. print("\nRequest methods:")
  40. for method, count in result["method_counter"].items():
  41.     print(f"{method}: {count}")
  42. print("\nTop URLs:")
  43. for url, count in result["url_counter"].most_common(3):
  44.     print(f"{url}: {count}")
  45. print("\nStatus codes:")
  46. for status, count in result["status_counter"].items():
  47.     print(f"{status}: {count}")
复制代码
  1. import re
  2. from collections import Counter
  3. def analyze_error_log(log):
  4.     # 提取错误类型和错误消息
  5.     pattern = r'\[(\w+)\]\s+(.+)'
  6.     matches = re.findall(pattern, log)
  7.    
  8.     # 统计错误类型
  9.     error_type_counter = Counter(match[0] for match in matches)
  10.    
  11.     # 统计错误消息
  12.     error_msg_counter = Counter(match[1] for match in matches)
  13.    
  14.     return {
  15.         "error_type_counter": error_type_counter,
  16.         "error_msg_counter": error_msg_counter
  17.     }
  18. # 测试
  19. log = """
  20. [ERROR] Failed to connect to database: Connection timeout
  21. [WARNING] Disk space is running low: 90% used
  22. [ERROR] Authentication failed for user: admin
  23. [INFO] Server started successfully
  24. [ERROR] Failed to connect to database: Connection timeout
  25. [WARNING] Memory usage is high: 85% used
  26. [ERROR] Authentication failed for user: guest
  27. [ERROR] Failed to connect to database: Connection timeout
  28. """
  29. result = analyze_error_log(log)
  30. print("Error types:")
  31. for error_type, count in result["error_type_counter"].items():
  32.     print(f"{error_type}: {count}")
  33. print("\nTop error messages:")
  34. for error_msg, count in result["error_msg_counter"].most_common(3):
  35.     print(f"{error_msg}: {count}")
复制代码
  1. import re
  2. from collections import defaultdict
  3. def analyze_app_log(log):
  4.     # 提取时间戳、日志级别和消息
  5.     pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \[(\w+)\] (.+)'
  6.     matches = re.findall(pattern, log)
  7.    
  8.     # 按小时统计日志数量
  9.     hourly_counts = defaultdict(int)
  10.     for timestamp, level, message in matches:
  11.         hour = timestamp.split(' ')[1].split(':')[0]
  12.         hourly_counts[hour] += 1
  13.    
  14.     # 统计日志级别
  15.     level_counts = defaultdict(int)
  16.     for timestamp, level, message in matches:
  17.         level_counts[level] += 1
  18.    
  19.     # 提取异常信息
  20.     exception_pattern = r'Exception: (.+)'
  21.     exceptions = re.findall(exception_pattern, log)
  22.    
  23.     return {
  24.         "hourly_counts": dict(hourly_counts),
  25.         "level_counts": dict(level_counts),
  26.         "exceptions": exceptions
  27.     }
  28. # 测试
  29. log = """
  30. 2023-07-15 10:30:45 [INFO] Application started
  31. 2023-07-15 10:31:12 [DEBUG] Loading configuration
  32. 2023-07-15 10:32:01 [ERROR] Failed to connect to database. Exception: Connection timeout
  33. 2023-07-15 10:33:22 [INFO] User logged in: admin
  34. 2023-07-15 10:34:05 [WARNING] Disk space is running low
  35. 2023-07-15 11:35:17 [ERROR] Authentication failed. Exception: Invalid credentials
  36. 2023-07-15 11:36:30 [INFO] User logged out: admin
  37. 2023-07-15 11:37:45 [DEBUG] Cleaning up resources
  38. """
  39. result = analyze_app_log(log)
  40. print("Hourly log counts:")
  41. for hour, count in sorted(result["hourly_counts"].items()):
  42.     print(f"{hour}:00 - {count} logs")
  43. print("\nLog level counts:")
  44. for level, count in result["level_counts"].items():
  45.     print(f"{level}: {count}")
  46. print("\nExceptions:")
  47. for exception in result["exceptions"]:
  48.     print(exception)
复制代码

Web爬虫中的文本处理

正则表达式在Web爬虫中也非常有用,可以帮助我们从HTML页面中提取所需的信息。下面是一些示例:
  1. import re
  2. import requests
  3. def extract_links(url):
  4.     # 获取网页内容
  5.     response = requests.get(url)
  6.     html = response.text
  7.    
  8.     # 提取所有链接
  9.     pattern = r'<a\s+(?:[^>]*?\s+)?href="([^"]*)"'
  10.     links = re.findall(pattern, html)
  11.    
  12.     return links
  13. # 测试
  14. url = "https://www.example.com"
  15. links = extract_links(url)
  16. for link in links[:10]:  # 只显示前10个链接
  17.     print(link)
复制代码
  1. import re
  2. import requests
  3. def extract_images(url):
  4.     # 获取网页内容
  5.     response = requests.get(url)
  6.     html = response.text
  7.    
  8.     # 提取所有图片
  9.     pattern = r'<img\s+(?:[^>]*?\s+)?src="([^"]*)"'
  10.     images = re.findall(pattern, html)
  11.    
  12.     return images
  13. # 测试
  14. url = "https://www.example.com"
  15. images = extract_images(url)
  16. for image in images[:10]:  # 只显示前10个图片
  17.     print(image)
复制代码
  1. import re
  2. import requests
  3. def extract_emails(url):
  4.     # 获取网页内容
  5.     response = requests.get(url)
  6.     html = response.text
  7.    
  8.     # 提取所有电子邮件地址
  9.     pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
  10.     emails = re.findall(pattern, html)
  11.    
  12.     return emails
  13. # 测试
  14. url = "https://www.example.com"
  15. emails = extract_emails(url)
  16. for email in emails:
  17.     print(email)
复制代码
  1. import re
  2. import requests
  3. def extract_phone_numbers(url):
  4.     # 获取网页内容
  5.     response = requests.get(url)
  6.     html = response.text
  7.    
  8.     # 提取所有电话号码(支持多种格式)
  9.     pattern = r"(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})"
  10.     phone_numbers = re.findall(pattern, html)
  11.    
  12.     # 格式化电话号码
  13.     formatted_numbers = []
  14.     for groups in phone_numbers:
  15.         country_code, area_code, prefix, line_number = groups
  16.         if country_code:
  17.             formatted_number = f"+{country_code} ({area_code}) {prefix}-{line_number}"
  18.         else:
  19.             formatted_number = f"({area_code}) {prefix}-{line_number}"
  20.         formatted_numbers.append(formatted_number)
  21.    
  22.     return formatted_numbers
  23. # 测试
  24. url = "https://www.example.com"
  25. phone_numbers = extract_phone_numbers(url)
  26. for phone_number in phone_numbers:
  27.     print(phone_number)
复制代码
  1. import re
  2. import requests
  3. def extract_tables(url):
  4.     # 获取网页内容
  5.     response = requests.get(url)
  6.     html = response.text
  7.    
  8.     # 提取所有表格
  9.     table_pattern = r'<table[^>]*>(.*?)</table>'
  10.     tables = re.findall(table_pattern, html, re.DOTALL)
  11.    
  12.     # 提取表格数据
  13.     all_tables_data = []
  14.     for table in tables:
  15.         # 提取行
  16.         row_pattern = r'<tr[^>]*>(.*?)</tr>'
  17.         rows = re.findall(row_pattern, table, re.DOTALL)
  18.         
  19.         # 提取单元格数据
  20.         table_data = []
  21.         for row in rows:
  22.             # 提取表头或单元格
  23.             cell_pattern = r'<t[hd][^>]*>(.*?)</t[hd]>'
  24.             cells = re.findall(cell_pattern, row, re.DOTALL)
  25.             
  26.             # 清理HTML标签
  27.             cleaned_cells = []
  28.             for cell in cells:
  29.                 # 移除HTML标签
  30.                 cleaned_cell = re.sub(r'<[^>]+>', '', cell)
  31.                 # 移除多余的空白字符
  32.                 cleaned_cell = re.sub(r'\s+', ' ', cleaned_cell).strip()
  33.                 cleaned_cells.append(cleaned_cell)
  34.             
  35.             if cleaned_cells:  # 只添加非空行
  36.                 table_data.append(cleaned_cells)
  37.         
  38.         if table_data:  # 只添加非空表格
  39.             all_tables_data.append(table_data)
  40.    
  41.     return all_tables_data
  42. # 测试
  43. url = "https://www.example.com"
  44. tables = extract_tables(url)
  45. for i, table in enumerate(tables):
  46.     print(f"Table {i+1}:")
  47.     for row in table:
  48.         print(row)
  49.     print()
复制代码

正则表达式工具和资源

在学习和使用正则表达式时,有一些工具和资源可以帮助我们提高效率和解决问题。下面是一些常用的正则表达式工具和资源:

在线正则表达式测试工具

1. Regex101(https://regex101.com/)支持多种正则表达式风格(PCRE、Python、Golang、JavaScript)提供详细的解释和调试信息支持代码生成和分享
2. 支持多种正则表达式风格(PCRE、Python、Golang、JavaScript)
3. 提供详细的解释和调试信息
4. 支持代码生成和分享
5. RegExr(https://regexr.com/)直观的界面,支持实时匹配提供正则表达式参考和示例支持保存和分享正则表达式
6. 直观的界面,支持实时匹配
7. 提供正则表达式参考和示例
8. 支持保存和分享正则表达式
9. Debuggex(https://www.debuggex.com/)可视化正则表达式,帮助理解复杂模式支持Ruby、Python、Perl和PCRE风格提供实时匹配和错误提示
10. 可视化正则表达式,帮助理解复杂模式
11. 支持Ruby、Python、Perl和PCRE风格
12. 提供实时匹配和错误提示
13. Regex Pal(https://www.regexpal.com/)简洁的界面,支持实时匹配支持高亮显示匹配结果提供基本的正则表达式参考
14. 简洁的界面,支持实时匹配
15. 支持高亮显示匹配结果
16. 提供基本的正则表达式参考

Regex101(https://regex101.com/)

• 支持多种正则表达式风格(PCRE、Python、Golang、JavaScript)
• 提供详细的解释和调试信息
• 支持代码生成和分享

RegExr(https://regexr.com/)

• 直观的界面,支持实时匹配
• 提供正则表达式参考和示例
• 支持保存和分享正则表达式

Debuggex(https://www.debuggex.com/)

• 可视化正则表达式,帮助理解复杂模式
• 支持Ruby、Python、Perl和PCRE风格
• 提供实时匹配和错误提示

Regex Pal(https://www.regexpal.com/)

• 简洁的界面,支持实时匹配
• 支持高亮显示匹配结果
• 提供基本的正则表达式参考

正则表达式学习资源

1. Regular-Expressions.info(https://www.regular-expressions.info/)全面的正则表达式教程和参考涵盖多种编程语言的正则表达式实现提供大量示例和最佳实践
2. 全面的正则表达式教程和参考
3. 涵盖多种编程语言的正则表达式实现
4. 提供大量示例和最佳实践
5. MDN Web Docs - Regular Expressions(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)Mozilla开发者网络提供的JavaScript正则表达式指南详细的语法说明和示例适合Web开发者学习
6. Mozilla开发者网络提供的JavaScript正则表达式指南
7. 详细的语法说明和示例
8. 适合Web开发者学习
9. Python re Module Documentation(https://docs.python.org/3/library/re.html)Python官方文档中关于re模块的说明详细的API文档和示例适合Python开发者学习
10. Python官方文档中关于re模块的说明
11. 详细的API文档和示例
12. 适合Python开发者学习
13. Java Pattern Class Documentation(https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html)Java官方文档中关于Pattern类的说明详细的语法说明和API文档适合Java开发者学习
14. Java官方文档中关于Pattern类的说明
15. 详细的语法说明和API文档
16. 适合Java开发者学习

Regular-Expressions.info(https://www.regular-expressions.info/)

• 全面的正则表达式教程和参考
• 涵盖多种编程语言的正则表达式实现
• 提供大量示例和最佳实践

MDN Web Docs - Regular Expressions(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)

• Mozilla开发者网络提供的JavaScript正则表达式指南
• 详细的语法说明和示例
• 适合Web开发者学习

Python re Module Documentation(https://docs.python.org/3/library/re.html)

• Python官方文档中关于re模块的说明
• 详细的API文档和示例
• 适合Python开发者学习

Java Pattern Class Documentation(https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html)

• Java官方文档中关于Pattern类的说明
• 详细的语法说明和API文档
• 适合Java开发者学习

正则表达式书籍

1. 《精通正则表达式》(Mastering Regular Expressions) - Jeffrey E.F. Friedl正则表达式领域的经典著作深入讲解正则表达式的原理和应用适合希望深入理解正则表达式的读者
2. 正则表达式领域的经典著作
3. 深入讲解正则表达式的原理和应用
4. 适合希望深入理解正则表达式的读者
5. 《正则表达式必知必会》(Regular Expressions Pocket Reference) - Tony Stubblebine简洁实用的正则表达式参考手册包含常用正则表达式模式和示例适合需要快速查阅正则表达式语法的读者
6. 简洁实用的正则表达式参考手册
7. 包含常用正则表达式模式和示例
8. 适合需要快速查阅正则表达式语法的读者
9. 《正则表达式入门经典》(Beginning Regular Expressions) - Andrew Watt适合初学者的正则表达式入门书籍通过实例讲解正则表达式的基本概念和应用适合没有编程基础的读者
10. 适合初学者的正则表达式入门书籍
11. 通过实例讲解正则表达式的基本概念和应用
12. 适合没有编程基础的读者

《精通正则表达式》(Mastering Regular Expressions) - Jeffrey E.F. Friedl

• 正则表达式领域的经典著作
• 深入讲解正则表达式的原理和应用
• 适合希望深入理解正则表达式的读者

《正则表达式必知必会》(Regular Expressions Pocket Reference) - Tony Stubblebine

• 简洁实用的正则表达式参考手册
• 包含常用正则表达式模式和示例
• 适合需要快速查阅正则表达式语法的读者

《正则表达式入门经典》(Beginning Regular Expressions) - Andrew Watt

• 适合初学者的正则表达式入门书籍
• 通过实例讲解正则表达式的基本概念和应用
• 适合没有编程基础的读者

正则表达式库和工具

1. Regex Golf(https://regex.alf.nu/)一个有趣的游戏,通过编写正则表达式来解决特定问题帮助提高正则表达式技能适合有一定基础的读者练习
2. 一个有趣的游戏,通过编写正则表达式来解决特定问题
3. 帮助提高正则表达式技能
4. 适合有一定基础的读者练习
5. Exrex(https://github.com/asciimoo/exrex)一个Python库,可以从正则表达式生成随机字符串帮助测试和理解正则表达式适合需要测试正则表达式的开发者
6. 一个Python库,可以从正则表达式生成随机字符串
7. 帮助测试和理解正则表达式
8. 适合需要测试正则表达式的开发者
9. Regexp::Common(https://metacpan.org/pod/Regexp::Common)一个Perl模块,提供常用的正则表达式模式包含大量预定义的正则表达式适合Perl开发者使用
10. 一个Perl模块,提供常用的正则表达式模式
11. 包含大量预定义的正则表达式
12. 适合Perl开发者使用
13. VerbalExpressions(https://github.com/VerbalExpressions)一个跨平台的库,提供构建正则表达式的流畅接口使正则表达式更易读和维护支持多种编程语言
14. 一个跨平台的库,提供构建正则表达式的流畅接口
15. 使正则表达式更易读和维护
16. 支持多种编程语言

Regex Golf(https://regex.alf.nu/)

• 一个有趣的游戏,通过编写正则表达式来解决特定问题
• 帮助提高正则表达式技能
• 适合有一定基础的读者练习

Exrex(https://github.com/asciimoo/exrex)

• 一个Python库,可以从正则表达式生成随机字符串
• 帮助测试和理解正则表达式
• 适合需要测试正则表达式的开发者

Regexp::Common(https://metacpan.org/pod/Regexp::Common)

• 一个Perl模块,提供常用的正则表达式模式
• 包含大量预定义的正则表达式
• 适合Perl开发者使用

VerbalExpressions(https://github.com/VerbalExpressions)

• 一个跨平台的库,提供构建正则表达式的流畅接口
• 使正则表达式更易读和维护
• 支持多种编程语言

总结与展望

正则表达式是一种强大而灵活的文本处理工具,它能够帮助我们以简洁的方式描述和匹配复杂的文本模式,从而极大地提高工作效率。通过本文的学习,我们从正则表达式的基础概念讲起,逐步深入到高级技巧,通过丰富的实例和详细的代码演示,全面掌握了正则表达式的使用方法。

正则表达式的优势

1. 简洁高效:正则表达式可以用简短的代码描述复杂的文本模式,大大减少了代码量。
2. 跨平台:几乎所有主流编程语言都支持正则表达式,使其成为一种通用的文本处理工具。
3. 功能强大:正则表达式支持复杂的模式匹配,可以处理各种文本处理需求。
4. 灵活多变:正则表达式提供了丰富的元字符和语法,可以灵活地应对各种文本处理场景。

正则表达式的局限性

1. 可读性差:复杂的正则表达式往往难以理解和维护。
2. 性能问题:不当的正则表达式可能导致性能问题,甚至造成”灾难性回溯”。
3. 学习曲线陡峭:正则表达式的语法和概念相对复杂,需要一定的学习成本。
4. 不适合所有场景:对于一些复杂的文本处理任务,可能需要结合其他工具和方法。

正则表达式的最佳实践

1. 保持简洁:尽量使用简单明了的正则表达式,避免不必要的复杂性。
2. 添加注释:对于复杂的正则表达式,添加注释以提高可读性。
3. 测试验证:使用测试工具验证正则表达式的正确性和性能。
4. 考虑替代方案:对于一些复杂的文本处理任务,考虑使用专门的解析器或工具。

正则表达式的未来发展趋势

1. 更好的可读性:未来的正则表达式可能会提供更好的语法和工具,以提高可读性和可维护性。
2. 更高的性能:正则表达式引擎可能会进一步优化,提供更高的匹配效率。
3. 更丰富的功能:正则表达式可能会增加更多的功能和语法,以应对更复杂的文本处理需求。
4. 更好的集成:正则表达式可能会更好地与其他工具和技术集成,提供更全面的文本处理解决方案。

总之,正则表达式是一种强大而灵活的文本处理工具,掌握正则表达式可以帮助我们更高效地处理文本数据,提高工作效率。通过不断学习和实践,我们可以成为正则表达式的高手,轻松应对各种文本处理挑战。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

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

本版积分规则