正则表达式入门:Python ‘ re ‘ 模块详解

正则表达式(Regular Expression,简称 re)是一种强大而灵活的工具,广泛用于字符串匹配、替换和分割等操作,尤其在处理网页爬虫数据时非常有用。Python 提供了 " re " 模块来支持正则表达式的使用,本文将结合常见的用法和示例,带你快速入门。

正则表达式的常用方法

匹配字符串

1. ' search() '
' search() ' 方法用于在字符串中查找符合正则表达式的第一个匹配项。它从字符串的任意位置开始匹配,返回一个 ' Match ' 对象,或者在没有匹配时返回 ' None '。

import re

pattern = r"\d+"  # 匹配一个或多个数字
string = "The price is 100 dollars."

match = re.search(pattern, string)
if match:
    print(f"Found: {match.group()} at position {match.start()}-{match.end()}")
else:
    print("No match found!")

2. ' match() ' 
' match() ' 方法用于从字符串的开头匹配,如果开头不符合正则表达式,则返回 ' None '。

pattern = r"\d+"  # 匹配一个或多个数字
string = "100 dollars"

match = re.match(pattern, string)
if match:
    print(f"Matched: {match.group()}")
else:
    print("No match found!")

3. ' fullmatch() '
' fullmatch() ' 方法要求整个字符串完全符合正则表达式,否则返回 ' None '。

pattern = r"\d+"  # 匹配一个或多个数字
string = "100"

match = re.fullmatch(pattern, string)
if match:
    print(f"Full match: {match.group()}")
else:
    print("No full match!")

4. ' findall() '
' findall() ' 方法返回一个列表,包含字符串中所有符合正则表达式的匹配项。

pattern = r"\d+"  # 匹配一个或多个数字
string = "There are 100 apples and 200 oranges."

matches = re.findall(pattern, string)
print(f"All matches: {matches}")

5. ' finditer() '
' finditer() ' 方法返回一个迭代器,每个元素都是一个 ' Match ' 对象,表示字符串中每一个匹配项。

pattern = r"\d+"  # 匹配一个或多个数字
string = "There are 100 apples and 200 oranges."

matches = re.finditer(pattern, string)
for match in matches:
    print(f"Found: {match.group()} at position {match.start()}-{match.end()}")

替换字符串

1. ' sub() '
' sub() ' 方法用于替换字符串中所有符合正则表达式的部分,返回替换后的新字符串。

pattern = r"\d+"  # 匹配一个或多个数字
string = "There are 100 apples and 200 oranges."
replacement = "many"

new_string = re.sub(pattern, replacement, string)
print(new_string)  # 输出:There are many apples and many oranges.

2. ' subn() '
' subn() ' 方法与 ' sub() ' 类似,但它返回一个元组,包括替换后的字符串和替换次数。

pattern = r"\d+"  # 匹配一个或多个数字
string = "There are 100 apples and 200 oranges."
replacement = "many"

new_string, count = re.subn(pattern, replacement, string)
print(new_string)  # 输出:There are many apples and many oranges.
print(f"Replacements made: {count}")

分割字符串


 1. ' split() '
' split() ' 方法用于根据正则表达式匹配项来分割字符串,返回分割后的列表。

pattern = r"\s+"  # 匹配一个或多个空白字符
string = "This is a test."

parts = re.split(pattern, string)
print(parts)  # 输出:['This', 'is', 'a', 'test.']

正则表达式中的特殊字符

在编写正则表达式时,理解特殊字符的用法非常重要。以下是一些常用的特殊字符:

' \w ':匹配字母、数字、下划线。
' \W ':匹配非字母、数字、下划线的字符。
' \d ':匹配数字

' \D ':匹配非数字字符。
' \s ':匹配空白字符(包括空格、制表符等)。
' \S ':匹配非空白字符。
' . ':匹配除换行符 ' \n ' 之外的任意字符(如果使用 ' re.S ' 标志,可以匹配包括换行符在内的所有字符)。
' ^ ':匹配字符串的开头(如果使用 ' re.M ' 标志,可以匹配每一行的开头)。
' $ ':匹配字符串的结尾(如果使用 ' re.M ' 标志,可以匹配每一行的结尾)。

贪婪与非贪婪匹配

正则表达式中的量词(如 ' * '、' + ' 和 ' ? ')默认情况下是贪婪的,它们会尽可能多地匹配字符。要进行非贪婪(尽可能少的匹配),可以在量词后加上 ' ? '。

' * ':匹配前面的字符 0 次或多次。
' + ':匹配前面的字符 1 次或多次。
' ? ':匹配前面的字符 0 次或 1 次。
' {n} ':匹配前面的字符恰好 n 次。
' {m,n} ':匹配前面的字符至少 m 次,至多 n 次。
' {m,n}? ':非贪婪地匹配前面的字符至少 m 次,至多 n 次。

字符类和分组

' [] ':定义一个字符类,匹配其中的任意一个字符。例如,' [aeiou] ' 匹配任意一个元音字母。
' | ':表示逻辑或,匹配 ' | ' 左右两边的任意一个表达式。例如,' a|b ' 匹配 "a" 或 "b"。
' () ':用于分组,可以将多个字符组合在一起作为一个单元,或者用于提取匹配到的子串。

示例:结合网页爬虫数据解析假设我们正在处理一段 HTML 数据,想要提取所有的 ' <a> ' 标签中的链接。我们可以使用正则表达式来简单地实现这一操作。

import re

html_data = '''
<a href="https://example.com">Example</a>
<a href="https://another-example.com">Another Example</a>
'''

# 正则表达式模式,用于匹配 href 属性中的 URL
pattern = r'href="(https?://[^"]+)"'

# 使用 findall() 提取所有匹配的 URL
urls = re.findall(pattern, html_data)
print(urls)

在这个示例中,' (https?://[^"]+) ' 部分表示匹配 "http://" 或 "https://" 开头,后面跟随任意非引号的字符串,直到下一个引号为止。通过 ' re.findall() ',我们可以轻松提取出所有符合条件的链接。

总结

Python 的 ' re ' 模块提供了强大的正则表达式支持,使得字符串的匹配、替换和分割操作变得非常灵活和高效。无论是在处理爬虫数据还是在其他文本处理任务中,掌握正则表达式都将大大提升你的工作效率。

记住,正则表达式虽然强大,但也容易变得复杂,因此在使用时应尽量保持模式的简洁和可读性。同时,随着经验的积累,你会逐渐发现正则表达式的更多妙用。Happy coding!

  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值