活动公告

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

正则表达式与类库实战技巧让文本处理事半功倍编程开发必备知识详解从入门到精通应用案例分享提升编程效率

SunJu_FaceMall

3万

主题

3148

科技点

3万

积分

执行版主

碾压王

积分
32876

塔罗立华奏

执行版主 发表于 2025-9-5 20:40:01 | 显示全部楼层 |阅读模式

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

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

x
引言

正则表达式(Regular Expression,简称regex或regexp)是一种强大的文本处理工具,它使用特定的字符序列来描述和匹配字符串模式。在当今数据爆炸的时代,文本处理已成为编程开发中不可或缺的技能,而正则表达式则是文本处理的利器。无论是数据验证、信息提取、文本替换还是复杂的模式匹配,正则表达式都能帮助开发者以简洁高效的方式完成任务。

本文将从正则表达式的基础知识入手,逐步深入到高级技巧和实战应用,帮助读者全面掌握这一编程必备技能,并通过丰富的案例分享,展示如何利用正则表达式及其类库提升编程效率,实现文本处理的事半功倍。

正则表达式基础

什么是正则表达式

正则表达式是一种由普通字符(如字母、数字)和特殊字符(称为”元字符”)组成的文字模式,它描述了一种字符串匹配的模式。正则表达式可以用来检查一个字符串是否含有某种子串、将匹配的子串替换或者从某个字符串中取出符合某个条件的子串等。

基本语法

普通字符包括所有可打印和不可打印的字符,包括所有大小写字母、数字、标点符号和一些其他符号。例如,正则表达式"cat"可以匹配字符串中的”cat”。

元字符是正则表达式中具有特殊含义的字符。以下是常用的元字符及其功能:

• .:匹配除换行符外的任意单个字符
• ^:匹配字符串的开始位置
• $:匹配字符串的结束位置
• *:匹配前面的子表达式零次或多次
• +:匹配前面的子表达式一次或多次
• ?:匹配前面的子表达式零次或一次
• {n}:匹配前面的子表达式恰好n次
• {n,}:匹配前面的子表达式至少n次
• {n,m}:匹配前面的子表达式至少n次,最多m次
• []:定义字符集,匹配其中的任意一个字符
• |:选择符,匹配左右两边表达式中的任意一个
• ():分组,将括号内的表达式作为一个整体
• \:转义字符,用于匹配特殊字符本身

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

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

量词

量词用来指定匹配的次数:

• *:匹配零次或多次
• +:匹配一次或多次
• ?:匹配零次或一次
• {n}:匹配恰好n次
• {n,}:匹配至少n次
• {n,m}:匹配至少n次,最多m次

贪婪与非贪婪模式

默认情况下,量词是”贪婪”的,即它们会尽可能多地匹配字符。例如,正则表达式a.*b对于字符串”aabab”,会匹配整个”aabab”,而不是”ab”。

如果需要”非贪婪”模式,可以在量词后面加上?。例如,a.*?b对于字符串”aabab”,会先匹配”ab”,然后是下一个”ab”。

简单示例

让我们通过一些简单的示例来理解正则表达式的基本用法:
  1. import re
  2. # 匹配数字
  3. pattern = r'\d+'
  4. text = "There are 123 apples and 456 oranges."
  5. result = re.findall(pattern, text)
  6. print(result)  # 输出: ['123', '456']
  7. # 匹配邮箱地址
  8. pattern = r'\w+@\w+\.\w+'
  9. text = "Contact us at info@example.com or support@company.org"
  10. result = re.findall(pattern, text)
  11. print(result)  # 输出: ['info@example.com', 'support@company.org']
  12. # 匹配HTML标签
  13. pattern = r'<[^>]+>'
  14. text = "<div>This is a <b>bold</b> text</div>"
  15. result = re.findall(pattern, text)
  16. print(result)  # 输出: ['<div>', '<b>', '</b>', '</div>']
复制代码

正则表达式高级技巧

分组与捕获

分组是正则表达式中的一个重要概念,它允许我们将多个字符作为一个单元进行处理。使用圆括号()可以创建一个分组。

捕获组不仅可以将多个字符作为一个单元,还可以捕获匹配的文本,以便后续使用。捕获组按照从左到右的顺序编号,从1开始。
  1. import re
  2. # 提取日期中的年、月、日
  3. pattern = r'(\d{4})-(\d{2})-(\d{2})'
  4. text = "Today's date is 2023-07-15."
  5. match = re.search(pattern, text)
  6. if match:
  7.     year = match.group(1)  # 第一个捕获组
  8.     month = match.group(2)  # 第二个捕获组
  9.     day = match.group(3)  # 第三个捕获组
  10.     print(f"Year: {year}, Month: {month}, Day: {day}")
  11.     # 输出: Year: 2023, Month: 07, Day: 15
复制代码

有时候我们只需要分组功能,而不需要捕获匹配的文本。这时可以使用非捕获组(?:...),它可以提高正则表达式的性能。
  1. import re
  2. # 使用非捕获组匹配重复的单词
  3. pattern = r'\b(\w+)(?:\s+\1\b)+'
  4. text = "hello hello world world world"
  5. matches = re.finditer(pattern, text)
  6. for match in matches:
  7.     print(f"Found repeated word: {match.group(1)}")
  8.     # 输出: Found repeated word: hello
  9.     # 输出: Found repeated word: world
复制代码

断言

断言(Assertion)是正则表达式中的一种高级特性,它用于匹配某些条件,但不消耗字符,即不会将匹配的字符包含在最终结果中。

正向先行断言(?=...)表示当前位置后面的字符串必须匹配指定的模式,但不包含在匹配结果中。
  1. import re
  2. # 匹配后面跟着"apple"的单词
  3. pattern = r'\w+(?= apple)'
  4. text = "I like red apple and green apple."
  5. matches = re.findall(pattern, text)
  6. print(matches)  # 输出: ['red', 'green']
复制代码

负向先行断言(?!...)表示当前位置后面的字符串不能匹配指定的模式。
  1. import re
  2. # 匹配不以"un"开头的单词
  3. pattern = r'\b(?!un)\w+\b'
  4. text = "happy unhappy able unable"
  5. matches = re.findall(pattern, text)
  6. print(matches)  # 输出: ['happy', 'able']
复制代码

正向后行断言(?<=...)表示当前位置前面的字符串必须匹配指定的模式,但不包含在匹配结果中。
  1. import re
  2. # 匹配前面是"$"的数字
  3. pattern = r'(?<=\$)\d+'
  4. text = "Price: $100, $200, $300"
  5. matches = re.findall(pattern, text)
  6. print(matches)  # 输出: ['100', '200', '300']
复制代码

负向后行断言(?<!...)表示当前位置前面的字符串不能匹配指定的模式。
  1. import re
  2. # 匹配不以数字开头的单词
  3. pattern = r'(?<!\d)\b\w+\b'
  4. text = "123abc abc 456def"
  5. matches = re.findall(pattern, text)
  6. print(matches)  # 输出: ['abc']
复制代码

反向引用

反向引用允许我们在正则表达式中引用前面捕获组匹配的内容。使用\1、\2等表示引用第1、第2个捕获组。
  1. import re
  2. # 匹配重复的单词
  3. pattern = r'\b(\w+)\s+\1\b'
  4. text = "hello world world hello"
  5. matches = re.finditer(pattern, text)
  6. for match in matches:
  7.     print(f"Found repeated word: {match.group(1)}")
  8.     # 输出: Found repeated word: world
复制代码

条件匹配

正则表达式支持条件匹配,格式为(?(condition)true-pattern|false-pattern),其中condition可以是一个捕获组的编号或名称。
  1. import re
  2. # 匹配带有引号的字符串,如果以双引号开始,则以双引号结束;如果以单引号开始,则以单引号结束
  3. pattern = r'^(?:(["\']))(.*?)\1$'
  4. text1 = '"Hello, world!"'
  5. text2 = "'Hello, world!'"
  6. text3 = '"Hello, world!''
  7. print(re.match(pattern, text1).group(2))  # 输出: Hello, world!
  8. print(re.match(pattern, text2).group(2))  # 输出: Hello, world!
  9. print(re.match(pattern, text3))  # 输出: None
复制代码

注释与模式修饰符

在复杂的正则表达式中,可以使用(?#comment)添加注释,提高可读性。
  1. import re
  2. # 带注释的正则表达式
  3. pattern = r'\b(?#Word boundary)(\w+)(?#Capture word)(?:\s+\1\b)+(?#One or more repeated words)'
  4. text = "hello hello world world world"
  5. matches = re.finditer(pattern, text)
  6. for match in matches:
  7.     print(f"Found repeated word: {match.group(1)}")
  8.     # 输出: Found repeated word: hello
  9.     # 输出: Found repeated word: world
复制代码

模式修饰符(也称为标志)可以改变正则表达式的匹配行为。常见的模式修饰符包括:

• i:不区分大小写匹配
• m:多行模式,使^和$匹配每行的开始和结束
• s:单行模式,使.匹配包括换行符在内的所有字符
• x:忽略模式中的空白和注释
• g:全局匹配,查找所有匹配项而不仅仅是第一个
  1. import re
  2. # 使用模式修饰符
  3. pattern = r'^hello'
  4. text = "Hello world\nhello there"
  5. # 不区分大小写匹配
  6. matches = re.findall(pattern, text, re.IGNORECASE | re.MULTILINE)
  7. print(matches)  # 输出: ['Hello', 'hello']
  8. # 单行模式,使.匹配包括换行符在内的所有字符
  9. pattern = r'<div>.*</div>'
  10. html = "<div>This is a\nmultiline\nstring</div>"
  11. match = re.search(pattern, html, re.DOTALL)
  12. if match:
  13.     print(match.group())  # 输出: <div>This is a
  14.                          # multiline
  15.                          # string</div>
复制代码

常用编程语言中的正则表达式类库

Python中的re模块

Python的re模块提供了正则表达式匹配操作。以下是re模块的主要函数和用法:

从字符串的起始位置匹配一个模式,如果起始位置匹配成功,则返回一个匹配对象,否则返回None。
  1. import re
  2. pattern = r'\d+'
  3. text = "123abc"
  4. match = re.match(pattern, text)
  5. if match:
  6.     print(f"Match found: {match.group()}")  # 输出: Match found: 123
  7. text = "abc123"
  8. match = re.match(pattern, text)
  9. if match:
  10.     print(f"Match found: {match.group()}")
  11. else:
  12.     print("No match found")  # 输出: No match found
复制代码

扫描整个字符串,返回第一个成功匹配的对象。
  1. import re
  2. pattern = r'\d+'
  3. text = "abc123def"
  4. match = re.search(pattern, text)
  5. if match:
  6.     print(f"Match found: {match.group()}")  # 输出: Match found: 123
复制代码

查找字符串中所有正则表达式匹配的子串,并返回一个列表。
  1. import re
  2. pattern = r'\d+'
  3. text = "abc123def456ghi"
  4. matches = re.findall(pattern, text)
  5. print(matches)  # 输出: ['123', '456']
复制代码

查找字符串中所有正则表达式匹配的子串,并返回一个迭代器。
  1. import re
  2. pattern = r'\d+'
  3. text = "abc123def456ghi"
  4. matches = re.finditer(pattern, text)
  5. for match in matches:
  6.     print(f"Match found: {match.group()} at position {match.start()}-{match.end()}")
  7.     # 输出: Match found: 123 at position 3-6
  8.     # 输出: Match found: 456 at position 9-12
复制代码

替换字符串中所有匹配的子串。
  1. import re
  2. pattern = r'\d+'
  3. text = "abc123def456ghi"
  4. result = re.sub(pattern, 'NUM', text)
  5. print(result)  # 输出: abcNUMdefNUMghi
复制代码

根据匹配的子串分割字符串。
  1. import re
  2. pattern = r'\d+'
  3. text = "abc123def456ghi"
  4. result = re.split(pattern, text)
  5. print(result)  # 输出: ['abc', 'def', 'ghi']
复制代码

如果需要多次使用同一个正则表达式,可以先编译它,以提高效率。
  1. import re
  2. pattern = re.compile(r'\d+')
  3. text1 = "abc123def"
  4. text2 = "ghi456jkl"
  5. match1 = pattern.search(text1)
  6. match2 = pattern.search(text2)
  7. print(match1.group())  # 输出: 123
  8. print(match2.group())  # 输出: 456
复制代码

JavaScript中的RegExp对象

JavaScript中的正则表达式可以通过RegExp对象或者字面量(/pattern/flags)来创建。
  1. // 使用RegExp构造函数
  2. let pattern1 = new RegExp('\\d+');
  3. // 使用字面量
  4. let pattern2 = /\d+/;
  5. // 带标志的正则表达式
  6. let pattern3 = /\d+/g;  // g表示全局匹配
复制代码
  1. // test()方法:测试字符串是否匹配模式
  2. let pattern = /\d+/;
  3. console.log(pattern.test('abc123'));  // 输出: true
  4. console.log(pattern.test('abcdef'));  // 输出: false
  5. // exec()方法:执行匹配,返回结果数组
  6. let text = 'abc123def456';
  7. let result;
  8. while ((result = pattern.exec(text)) !== null) {
  9.     console.log(`Found ${result[0]} at position ${result.index}`);
  10.     // 输出: Found 123 at position 3
  11.     // 输出: Found 456 at position 9
  12. }
复制代码
  1. // match()方法:返回匹配结果的数组
  2. let text = 'abc123def456';
  3. let pattern = /\d+/g;
  4. console.log(text.match(pattern));  // 输出: ['123', '456']
  5. // search()方法:返回第一个匹配的位置
  6. console.log(text.search(/\d+/));  // 输出: 3
  7. // replace()方法:替换匹配的子串
  8. console.log(text.replace(/\d+/g, 'NUM'));  // 输出: abcNUMdefNUM
  9. // split()方法:根据匹配分割字符串
  10. console.log(text.split(/\d+/));  // 输出: ['abc', 'def', '']
复制代码

Java中的Pattern和Matcher类

Java提供了java.util.regex包来处理正则表达式,主要包括Pattern和Matcher两个类。

Pattern类表示编译后的正则表达式模式。
  1. import java.util.regex.Pattern;
  2. // 编译正则表达式
  3. Pattern pattern = Pattern.compile("\\d+");
  4. // 使用标志
  5. Pattern patternIgnoreCase = Pattern.compile("abc", Pattern.CASE_INSENSITIVE);
复制代码

Matcher类用于执行匹配操作。
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3. String text = "abc123def456";
  4. Pattern pattern = Pattern.compile("\\d+");
  5. Matcher matcher = pattern.matcher(text);
  6. // 查找所有匹配
  7. while (matcher.find()) {
  8.     System.out.println("Found " + matcher.group() + " at position " + matcher.start() + "-" + matcher.end());
  9.     // 输出: Found 123 at position 3-6
  10.     // 输出: Found 456 at position 9-12
  11. }
  12. // matches()方法:尝试将整个区域与模式匹配
  13. System.out.println(Pattern.matches("\\d+", "123"));  // 输出: true
  14. System.out.println(Pattern.matches("\\d+", "abc123"));  // 输出: false
  15. // replaceAll()方法:替换所有匹配的子串
  16. String result = matcher.replaceAll("NUM");
  17. System.out.println(result);  // 输出: abcNUMdefNUM
复制代码
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3. String text = "John: 30, Jane: 25, Bob: 40";
  4. Pattern pattern = Pattern.compile("(\\w+): (\\d+)");
  5. Matcher matcher = pattern.matcher(text);
  6. while (matcher.find()) {
  7.     String name = matcher.group(1);  // 第一个捕获组
  8.     String age = matcher.group(2);   // 第二个捕获组
  9.     System.out.println(name + " is " + age + " years old.");
  10.     // 输出: John is 30 years old.
  11.     // 输出: Jane is 25 years old.
  12.     // 输出: Bob is 40 years old.
  13. }
复制代码

其他语言中的正则表达式支持

C#中的System.Text.RegularExpressions命名空间提供了正则表达式支持。
  1. using System;
  2. using System.Text.RegularExpressions;
  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         string text = "abc123def456";
  8.         
  9.         // IsMatch()方法:测试字符串是否匹配模式
  10.         Console.WriteLine(Regex.IsMatch(text, @"\d+"));  // 输出: True
  11.         
  12.         // Match()方法:返回第一个匹配
  13.         Match match = Regex.Match(text, @"\d+");
  14.         Console.WriteLine(match.Value);  // 输出: 123
  15.         
  16.         // Matches()方法:返回所有匹配
  17.         MatchCollection matches = Regex.Matches(text, @"\d+");
  18.         foreach (Match m in matches)
  19.         {
  20.             Console.WriteLine(m.Value);  // 输出: 123, 然后输出: 456
  21.         }
  22.         
  23.         // Replace()方法:替换匹配的子串
  24.         string result = Regex.Replace(text, @"\d+", "NUM");
  25.         Console.WriteLine(result);  // 输出: abcNUMdefNUM
  26.         
  27.         // Split()方法:根据匹配分割字符串
  28.         string[] parts = Regex.Split(text, @"\d+");
  29.         foreach (string part in parts)
  30.         {
  31.             Console.WriteLine(part);  // 输出: abc, def,
  32.         }
  33.     }
  34. }
复制代码

Ruby内置了对正则表达式的支持,语法简洁。
  1. text = "abc123def456"
  2. # 匹配操作
  3. if text =~ /\d+/
  4.   puts "Match found at position #{$~.begin(0)}"  # 输出: Match found at position 3
  5. end
  6. # match()方法
  7. match_data = text.match(/\d+/)
  8. puts match_data[0] if match_data  # 输出: 123
  9. # scan()方法:返回所有匹配
  10. matches = text.scan(/\d+/)
  11. puts matches.inspect  # 输出: ["123", "456"]
  12. # gsub()方法:替换所有匹配
  13. result = text.gsub(/\d+/, 'NUM')
  14. puts result  # 输出: abcNUMdefNUM
  15. # split()方法:根据匹配分割字符串
  16. parts = text.split(/\d+/)
  17. puts parts.inspect  # 输出: ["abc", "def", ""]
复制代码

PHP提供了preg_系列函数来处理正则表达式。
  1. <?php
  2. $text = "abc123def456";
  3. // preg_match():执行匹配
  4. if (preg_match('/\d+/', $text, $matches)) {
  5.     echo "Match found: " . $matches[0] . "\n";  // 输出: Match found: 123
  6. }
  7. // preg_match_all():执行全局匹配
  8. if (preg_match_all('/\d+/', $text, $matches)) {
  9.     print_r($matches[0]);  // 输出: Array ( [0] => 123 [1] => 456 )
  10. }
  11. // preg_replace():替换匹配的子串
  12. $result = preg_replace('/\d+/', 'NUM', $text);
  13. echo $result . "\n";  // 输出: abcNUMdefNUM
  14. // preg_split():根据匹配分割字符串
  15. $parts = preg_split('/\d+/', $text);
  16. print_r($parts);  // 输出: Array ( [0] => abc [1] => def [2] => )
  17. ?>
复制代码

实战案例分享

数据验证

正则表达式在数据验证方面有着广泛的应用,可以高效地验证各种格式的数据。
  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.     return False
  7. # 测试
  8. emails = [
  9.     "user@example.com",
  10.     "user.name@sub.domain.co.uk",
  11.     "invalid.email@.com",
  12.     "another.invalid@domain",
  13.     "yet.another@domain."
  14. ]
  15. for email in emails:
  16.     print(f"{email}: {'Valid' if validate_email(email) else 'Invalid'}")
  17. # 输出:
  18. # user@example.com: Valid
  19. # user.name@sub.domain.co.uk: Valid
  20. # invalid.email@.com: Invalid
  21. # another.invalid@domain: Invalid
  22. # yet.another@domain.: Invalid
复制代码
  1. import re
  2. def validate_phone(phone):
  3.     # 支持多种格式:(123) 456-7890, 123-456-7890, 123.456.7890, 1234567890
  4.     pattern = r'^(\+\d{1,2}\s?)?(\(\d{3}\)|\d{3})[\s.-]?\d{3}[\s.-]?\d{4}$'
  5.     if re.match(pattern, phone):
  6.         return True
  7.     return False
  8. # 测试
  9. phones = [
  10.     "(123) 456-7890",
  11.     "123-456-7890",
  12.     "123.456.7890",
  13.     "1234567890",
  14.     "+1 123 456 7890",
  15.     "123-456-789"
  16. ]
  17. for phone in phones:
  18.     print(f"{phone}: {'Valid' if validate_phone(phone) else 'Invalid'}")
  19. # 输出:
  20. # (123) 456-7890: Valid
  21. # 123-456-7890: Valid
  22. # 123.456.7890: Valid
  23. # 1234567890: Valid
  24. # +1 123 456 7890: Valid
  25. # 123-456-789: Invalid
复制代码
  1. import re
  2. def check_password_strength(password):
  3.     # 至少8个字符,包含大小写字母、数字和特殊字符
  4.     pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'
  5.     if re.match(pattern, password):
  6.         return "Strong"
  7.    
  8.     # 至少6个字符,包含字母和数字
  9.     pattern = r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$'
  10.     if re.match(pattern, password):
  11.         return "Medium"
  12.    
  13.     return "Weak"
  14. # 测试
  15. passwords = [
  16.     "Password123!",
  17.     "password123",
  18.     "123456",
  19.     "abcdef",
  20.     "Abc123"
  21. ]
  22. for password in passwords:
  23.     print(f"{password}: {check_password_strength(password)}")
  24. # 输出:
  25. # Password123!: Strong
  26. # password123: Medium
  27. # 123456: Weak
  28. # abcdef: Weak
  29. # Abc123: Medium
复制代码

文本提取与替换

正则表达式在文本提取与替换方面非常强大,可以处理复杂的文本操作。
  1. import re
  2. def extract_urls(text):
  3.     # 匹配HTTP/HTTPS URL
  4.     pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+[/\w .-]*\??[/\w .-=&%]*'
  5.     return re.findall(pattern, text)
  6. # 测试
  7. text = """
  8. Visit our website at https://www.example.com for more information.
  9. You can also check out our blog at http://blog.example.com/posts/latest.
  10. For support, email us at support@example.com or visit https://help.example.com/faq?id=123&lang=en.
  11. """
  12. urls = extract_urls(text)
  13. for url in urls:
  14.     print(url)
  15. # 输出:
  16. # https://www.example.com
  17. # http://blog.example.com/posts/latest
  18. # https://help.example.com/faq?id=123&lang=en
复制代码
  1. import re
  2. def extract_html_tags(html, tag):
  3.     # 提取指定HTML标签的内容
  4.     pattern = f'<{tag}[^>]*>(.*?)</{tag}>'
  5.     return re.findall(pattern, html, re.DOTALL)
  6. # 测试
  7. html = """
  8. <html>
  9. <head>
  10.     <title>Example Page</title>
  11. </head>
  12. <body>
  13.     <h1>Welcome to the Example Page</h1>
  14.     <p>This is a paragraph with <b>bold</b> text.</p>
  15.     <p>Another paragraph with <i>italic</i> text.</p>
  16. </body>
  17. </html>
  18. """
  19. print("Titles:", extract_html_tags(html, 'title'))
  20. print("Headings:", extract_html_tags(html, 'h1'))
  21. print("Paragraphs:", extract_html_tags(html, 'p'))
  22. print("Bold text:", extract_html_tags(html, 'b'))
  23. print("Italic text:", extract_html_tags(html, 'i'))
  24. # 输出:
  25. # Titles: ['Example Page']
  26. # Headings: ['Welcome to the Example Page']
  27. # Paragraphs: ['This is a paragraph with <b>bold</b> text.', 'Another paragraph with <i>italic</i> text.']
  28. # Bold text: ['bold']
  29. # Italic text: ['italic']
复制代码
  1. import re
  2. def clean_text(text):
  3.     # 移除多余的空格
  4.     text = re.sub(r'\s+', ' ', text)
  5.    
  6.     # 移除特殊字符,只保留字母、数字和标点
  7.     text = re.sub(r'[^\w\s.,!?;:\'"-]', '', text)
  8.    
  9.     # 确保标点符号前没有空格
  10.     text = re.sub(r'\s+([.,!?;:\'"-])', r'\1', text)
  11.    
  12.     # 确保标点符号后有一个空格
  13.     text = re.sub(r'([.,!?;:\'"-])(?=[^\s])', r'\1 ', text)
  14.    
  15.     return text.strip()
  16. # 测试
  17. text = "This   is a  test@ text with   extra spaces, and... weird@ punctuation!Let's clean it up."
  18. cleaned = clean_text(text)
  19. print(cleaned)
  20. # 输出: This is a test text with extra spaces, and... weird punctuation. Let's clean it up.
复制代码

日志分析

正则表达式在日志分析中非常有用,可以快速提取关键信息。
  1. import re
  2. def parse_apache_log(log_line):
  3.     # Apache Common Log Format
  4.     pattern = r'^(\S+) \S+ \S+ \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+) (\S+)" (\d{3}) (\d+|-)'
  5.     match = re.match(pattern, log_line)
  6.     if match:
  7.         return {
  8.             'ip': match.group(1),
  9.             'timestamp': match.group(2),
  10.             'method': match.group(3),
  11.             'path': match.group(4),
  12.             'protocol': match.group(5),
  13.             'status': match.group(6),
  14.             'size': match.group(7)
  15.         }
  16.     return None
  17. # 测试
  18. log_line = '127.0.0.1 - - [25/Dec/2021:10:00:00 +0000] "GET /index.html HTTP/1.1" 200 1234'
  19. parsed = parse_apache_log(log_line)
  20. if parsed:
  21.     for key, value in parsed.items():
  22.         print(f"{key}: {value}")
  23. # 输出:
  24. # ip: 127.0.0.1
  25. # timestamp: 25/Dec/2021:10:00:00 +0000
  26. # method: GET
  27. # path: /index.html
  28. # protocol: HTTP/1.1
  29. # status: 200
  30. # size: 1234
复制代码
  1. import re
  2. def extract_error_info(log_text):
  3.     # 匹配错误日志中的时间戳、错误级别和错误消息
  4.     pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}),\d{3} \[(\w+)\] (.+)$'
  5.     errors = []
  6.     for line in log_text.split('\n'):
  7.         match = re.match(pattern, line)
  8.         if match and match.group(2) in ['ERROR', 'WARN']:
  9.             errors.append({
  10.                 'timestamp': match.group(1),
  11.                 'level': match.group(2),
  12.                 'message': match.group(3)
  13.             })
  14.     return errors
  15. # 测试
  16. log_text = """
  17. 2021-12-25 10:00:00,123 INFO Application started
  18. 2021-12-25 10:01:00,456 DEBUG Processing request
  19. 2021-12-25 10:02:00,789 WARN Connection timeout
  20. 2021-12-25 10:03:00,012 ERROR Database connection failed
  21. 2021-12-25 10:04:00,345 INFO Retrying connection
  22. 2021-12-25 10:05:00,678 ERROR Connection failed again
  23. """
  24. errors = extract_error_info(log_text)
  25. for error in errors:
  26.     print(f"{error['timestamp']} [{error['level']}] {error['message']}")
  27. # 输出:
  28. # 2021-12-25 10:02:00,789 [WARN] Connection timeout
  29. # 2021-12-25 10:03:00,012 [ERROR] Database connection failed
  30. # 2021-12-25 10:05:00,678 [ERROR] Connection failed again
复制代码

网页爬虫中的文本处理

正则表达式在网页爬虫中常用于提取特定信息。
  1. import re
  2. def extract_links(html):
  3.     # 匹配href属性中的链接
  4.     pattern = r'<a\s+(?:[^>]*?\s+)?href="([^"]*)"'
  5.     return re.findall(pattern, html)
  6. # 测试
  7. html = """
  8. <html>
  9. <body>
  10.     <a href="https://www.example.com">Example</a>
  11.     <a href="/about">About Us</a>
  12.     <a href="contact.html">Contact</a>
  13.     <a href="https://www.google.com" target="_blank">Google</a>
  14. </body>
  15. </html>
  16. """
  17. links = extract_links(html)
  18. for link in links:
  19.     print(link)
  20. # 输出:
  21. # https://www.example.com
  22. # /about
  23. # contact.html
  24. # https://www.google.com
复制代码
  1. import re
  2. def extract_product_info(html):
  3.     products = []
  4.    
  5.     # 匹配产品块
  6.     product_pattern = r'<div class="product">(.*?)</div>\s*</div>'
  7.     product_blocks = re.findall(product_pattern, html, re.DOTALL)
  8.    
  9.     for block in product_blocks:
  10.         product = {}
  11.         
  12.         # 提取产品名称
  13.         name_match = re.search(r'<h2>(.*?)</h2>', block)
  14.         if name_match:
  15.             product['name'] = name_match.group(1)
  16.         
  17.         # 提取产品价格
  18.         price_match = re.search(r'<span class="price">\$(\d+\.\d{2})</span>', block)
  19.         if price_match:
  20.             product['price'] = float(price_match.group(1))
  21.         
  22.         # 提取产品描述
  23.         desc_match = re.search(r'<p class="description">(.*?)</p>', block, re.DOTALL)
  24.         if desc_match:
  25.             product['description'] = desc_match.group(1).strip()
  26.         
  27.         products.append(product)
  28.    
  29.     return products
  30. # 测试
  31. html = """
  32. <html>
  33. <body>
  34.     <h1>Products</h1>
  35.    
  36.     <div class="product">
  37.         <h2>Smartphone</h2>
  38.         <span class="price">$599.99</span>
  39.         <p class="description">
  40.             A powerful smartphone with a large display and advanced camera.
  41.         </p>
  42.     </div>
  43.    
  44.     <div class="product">
  45.         <h2>Laptop</h2>
  46.         <span class="price">$999.99</span>
  47.         <p class="description">
  48.             High-performance laptop for work and gaming.
  49.         </p>
  50.     </div>
  51. </body>
  52. </html>
  53. """
  54. products = extract_product_info(html)
  55. for product in products:
  56.     print(f"Name: {product['name']}")
  57.     print(f"Price: ${product['price']}")
  58.     print(f"Description: {product['description']}")
  59.     print("---")
  60. # 输出:
  61. # Name: Smartphone
  62. # Price: $599.99
  63. # Description: A powerful smartphone with a large display and advanced camera.
  64. # ---
  65. # Name: Laptop
  66. # Price: $999.99
  67. # Description: High-performance laptop for work and gaming.
  68. # ---
复制代码

性能优化技巧

正则表达式虽然强大,但在处理大量文本时可能会遇到性能问题。以下是一些优化正则表达式性能的技巧:

1. 避免回溯

回溯是正则表达式性能问题的常见原因。当正则表达式引擎尝试多种可能的匹配路径时,就会发生回溯。以下是一些减少回溯的技巧:
  1. import re
  2. import time
  3. # 低效方式:使用.匹配任意字符
  4. pattern1 = r'<div>.*</div>'
  5. # 高效方式:使用具体字符类
  6. pattern2 = r'<div>[^<]*</div>'
  7. html = "<div>" + "content" * 1000 + "</div>"
  8. # 测试性能
  9. start_time = time.time()
  10. re.search(pattern1, html)
  11. print(f"Pattern 1 time: {time.time() - start_time:.6f} seconds")
  12. start_time = time.time()
  13. re.search(pattern2, html)
  14. print(f"Pattern 2 time: {time.time() - start_time:.6f} seconds")
复制代码

原子组(?>...)可以防止回溯,一旦匹配就不会放弃已匹配的字符。
  1. import re
  2. # 普通分组
  3. pattern1 = r'(\d+)+a'
  4. # 原子组
  5. pattern2 = r'(?>\d+)+a'
  6. text = "1234567890" * 10 + "b"  # 注意:这个文本不匹配模式
  7. # 测试性能
  8. try:
  9.     re.search(pattern1, text)
  10. except re.error:
  11.     print("Pattern 1 caused a catastrophic backtracking!")
  12. try:
  13.     re.search(pattern2, text)
  14. except re.error:
  15.     print("Pattern 2 caused a catastrophic backtracking!")
复制代码

2. 使用非捕获组

如果不需要捕获匹配的文本,使用非捕获组(?:...)可以提高性能。
  1. import re
  2. import time
  3. # 使用捕获组
  4. pattern1 = r'(\d{4})-(\d{2})-(\d{2})'
  5. # 使用非捕获组
  6. pattern2 = r'(?:\d{4})-(?:\d{2})-(?:\d{2})'
  7. text = "2023-07-15 " * 10000
  8. # 测试性能
  9. start_time = time.time()
  10. re.findall(pattern1, text)
  11. print(f"Pattern 1 time: {time.time() - start_time:.6f} seconds")
  12. start_time = time.time()
  13. re.findall(pattern2, text)
  14. print(f"Pattern 2 time: {time.time() - start_time:.6f} seconds")
复制代码

3. 预编译正则表达式

如果多次使用同一个正则表达式,预编译它可以提高性能。
  1. import re
  2. import time
  3. text = "abc123def456ghi789" * 1000
  4. # 不预编译
  5. start_time = time.time()
  6. for _ in range(1000):
  7.     re.findall(r'\d+', text)
  8. print(f"Without compilation time: {time.time() - start_time:.6f} seconds")
  9. # 预编译
  10. pattern = re.compile(r'\d+')
  11. start_time = time.time()
  12. for _ in range(1000):
  13.     pattern.findall(text)
  14. print(f"With compilation time: {time.time() - start_time:.6f} seconds")
复制代码

4. 使用锚点

使用^和$锚点可以限制匹配范围,提高匹配效率。
  1. import re
  2. import time
  3. text = "abc123def456ghi789" * 1000
  4. # 不使用锚点
  5. pattern1 = r'\d+'
  6. # 使用锚点
  7. pattern2 = r'^\d+$'
  8. # 测试性能
  9. start_time = time.time()
  10. re.search(pattern1, text)
  11. print(f"Without anchors time: {time.time() - start_time:.6f} seconds")
  12. start_time = time.time()
  13. re.search(pattern2, text)
  14. print(f"With anchors time: {time.time() - start_time:.6f} seconds")
复制代码

5. 避免过度使用贪婪量词

贪婪量词(如.*、.+)会导致大量回溯,尽可能使用非贪婪量词(如.*?、.+?)或更具体的模式。
  1. import re
  2. import time
  3. html = "<div>" + "content" * 100 + "</div>" * 100
  4. # 贪婪量词
  5. pattern1 = r'<div>.*</div>'
  6. # 非贪婪量词
  7. pattern2 = r'<div>.*?</div>'
  8. # 测试性能
  9. start_time = time.time()
  10. re.findall(pattern1, html)
  11. print(f"Greedy quantifier time: {time.time() - start_time:.6f} seconds")
  12. start_time = time.time()
  13. re.findall(pattern2, html)
  14. print(f"Non-greedy quantifier time: {time.time() - start_time:.6f} seconds")
复制代码

常见问题与解决方案

1. 匹配换行符

默认情况下,.不匹配换行符。要匹配包括换行符在内的所有字符,可以使用[\s\S]或启用DOTALL模式。
  1. import re
  2. text = "Line 1\nLine 2\nLine 3"
  3. # 不匹配换行符
  4. pattern1 = r'Line 1.*Line 3'
  5. print(re.search(pattern1, text))  # 输出: None
  6. # 匹配换行符的方法1:使用[\s\S]
  7. pattern2 = r'Line 1[\s\S]*Line 3'
  8. print(re.search(pattern2, text).group())  # 输出: Line 1
  9.                                         # Line 2
  10.                                         # Line 3
  11. # 匹配换行符的方法2:启用DOTALL模式
  12. pattern3 = r'Line 1.*Line 3'
  13. print(re.search(pattern3, text, re.DOTALL).group())  # 输出: Line 1
  14.                                                     # Line 2
  15.                                                     # Line 3
复制代码

2. 处理Unicode字符

在处理Unicode字符时,需要确保正则表达式支持Unicode,并使用适当的字符类。
  1. import re
  2. text = "Hello 你好 こんにちは 안녕하세요"
  3. # 匹配所有单词(包括Unicode)
  4. pattern1 = r'\w+'
  5. print(re.findall(pattern1, text))  # 输出: ['Hello', '\u4f60\u597d', '\u3053\u3093\u306b\u3061\u306f', '\uc548\ub155\ud558\uc138\uc694']
  6. # 使用Unicode属性匹配特定语言的字符
  7. pattern2 = r'\p{Han}+'  # 匹配汉字
  8. print(re.findall(pattern2, text, re.UNICODE))  # 输出: ['你好']
  9. pattern3 = r'\p{Hiragana}+'  # 匹配平假名
  10. print(re.findall(pattern3, text, re.UNICODE))  # 输出: ['こんにちは']
  11. pattern4 = r'\p{Hangul}+'  # 匹配韩文
  12. print(re.findall(pattern4, text, re.UNICODE))  # 输出: ['안녕하세요']
复制代码

3. 处理嵌套结构

正则表达式不适合处理嵌套结构(如括号嵌套),因为它们无法计数。对于这种情况,最好使用专门的解析器。
  1. import re
  2. # 尝试匹配嵌套括号(不推荐)
  3. text = "((a + b) * (c - d))"
  4. pattern = r'\(([^()]|(?R))*\)'  # 使用递归模式(PCRE支持,Python不支持)
  5. # 在Python中,可以使用以下方法处理简单的嵌套结构
  6. def match_nested_parens(text):
  7.     stack = []
  8.     result = []
  9.     start = -1
  10.    
  11.     for i, char in enumerate(text):
  12.         if char == '(':
  13.             if not stack:
  14.                 start = i
  15.             stack.append(i)
  16.         elif char == ')':
  17.             if stack:
  18.                 stack.pop()
  19.                 if not stack:
  20.                     result.append(text[start:i+1])
  21.    
  22.     return result
  23. print(match_nested_parens(text))  # 输出: ['((a + b) * (c - d))']
复制代码

4. 处理大型文本

处理大型文本时,正则表达式可能会消耗大量内存。以下是一些解决方案:
  1. import re
  2. # 方法1:使用生成器逐行处理
  3. def process_large_file(file_path, pattern):
  4.     compiled_pattern = re.compile(pattern)
  5.     with open(file_path, 'r') as file:
  6.         for line in file:
  7.             match = compiled_pattern.search(line)
  8.             if match:
  9.                 yield match
  10. # 方法2:使用re.Scanner进行流式处理
  11. def tokenize_large_text(text):
  12.     scanner = re.Scanner([
  13.         (r'\d+', lambda scanner, token: ('NUMBER', token)),
  14.         (r'[a-zA-Z_]\w*', lambda scanner, token: ('IDENTIFIER', token)),
  15.         (r'[+\-*/]', lambda scanner, token: ('OPERATOR', token)),
  16.         (r'\s+', None),  # 忽略空白
  17.         (r'.', lambda scanner, token: ('UNKNOWN', token)),
  18.     ])
  19.    
  20.     return scanner.scan(text)[0]
  21. # 测试
  22. text = "x = 123 + 456"
  23. tokens = tokenize_large_text(text)
  24. print(tokens)
  25. # 输出: [('IDENTIFIER', 'x'), ('OPERATOR', '='), ('NUMBER', '123'), ('OPERATOR', '+'), ('NUMBER', '456')]
复制代码

5. 调试复杂正则表达式

调试复杂的正则表达式可能很困难。以下是一些调试技巧:
  1. import re
  2. # 使用re.DEBUG标志查看正则表达式的匹配过程
  3. pattern = r'(\w+)\s+\1'
  4. text = "hello hello world world"
  5. print("Debugging pattern:")
  6. re.compile(pattern, re.DEBUG)
  7. # 使用在线工具可视化正则表达式
  8. # 例如:https://regex101.com/, https://regexper.com/
  9. # 分解复杂正则表达式
  10. def complex_pattern_match(text):
  11.     # 第一步:匹配单词
  12.     word_pattern = r'\w+'
  13.     words = re.finditer(word_pattern, text)
  14.    
  15.     # 第二步:检查重复
  16.     prev_word = None
  17.     for match in words:
  18.         current_word = match.group()
  19.         if current_word == prev_word:
  20.             print(f"Found repeated word: {current_word} at position {match.start()}")
  21.         prev_word = current_word
  22. # 测试
  23. complex_pattern_match("hello hello world world")
  24. # 输出: Found repeated word: hello at position 6
  25. # 输出: Found repeated word: world at position 17
复制代码

总结与展望

正则表达式是一种强大的文本处理工具,掌握它可以帮助开发者高效地处理各种文本相关的任务。本文从正则表达式的基础知识入手,逐步介绍了高级技巧、常用编程语言中的正则表达式类库、实战案例以及性能优化技巧。

通过学习正则表达式,开发者可以:

1. 快速验证和格式化数据
2. 高效地提取和替换文本
3. 分析和处理日志文件
4. 在网页爬虫中提取关键信息
5. 优化文本处理性能

未来,随着自然语言处理和人工智能技术的发展,正则表达式可能会与这些技术结合,提供更强大的文本处理能力。同时,正则表达式引擎也在不断优化,提供更好的性能和更丰富的功能。

无论你是初学者还是有经验的开发者,掌握正则表达式都是提升编程效率的重要途径。希望本文能够帮助你更好地理解和应用正则表达式,在文本处理任务中事半功倍。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

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

本版积分规则