十分钟搞定Python进行正则表达式操作的35个常见操作示例

目录

1.简单的匹配

2.匹配所有出现

3.替换文本

4.拆分字符串

5.从字符串开头匹配

6.使用组

7.非贪婪匹配

8.匹配数字

9.匹配单词边界

10.忽略大小写匹配

11.匹配多行文本

12.替换匹配项的函数

13.匹配任意字符

14.匹配可选项

15.匹配前导空白字符

16.匹配结尾空白字符

17.匹配开头和结尾

18.匹配单个字符

19.匹配重复出现的字符

20.分组和命名组

21.断言匹配

22.负断言匹配

23.预搜索

24.负预搜索

25.查找所有字符

26.非数字字符

27.非单词字符

28.非空白字符

29.查找字符串中的位置

30.查找所有匹配的位置

31.反向查找

32.匹配不在某字符集中的字符

33.匹配 Unicode 字符

34.多种分隔符拆分字符串

35.搜索并替换多次



首先,导入正则表达式模块:

图片

import re

1.简单的匹配

pattern = r'\d+'  # 匹配一个或多个数字
text = "There are 123 apples"
match = re.search(pattern, text)
print(match.group())  # 输出: 123

2.匹配所有出现

matches = re.findall(pattern, text)
print(matches)  # 输出: ['123']

3.替换文本

new_text = re.sub(pattern, '456', text)
print(new_text)  # 输出: There are 456 apples

4.拆分字符串

split_text = re.split(r'\s+', text)
print(split_text)  # 输出: ['There', 'are', '123', 'apples']

5.从字符串开头匹配

match = re.match(r'There', text)
print(match.group())  # 输出: There

6.使用组

pattern = r'(\d+)\s+apples'
match = re.search(pattern, text)
print(match.group(1))  # 输出: 123

7.非贪婪匹配

pattern = r'<.*?>'
html = "<div><span>Test</span></div>"
match = re.search(pattern, html)
print(match.group())  # 输出: <div>

8.匹配数字

pattern = r'\d+'
numbers = re.findall(pattern, "There are 3 cats and 4 dogs")
print(numbers)  # 输出: ['3', '4']

9.匹配单词边界

pattern = r'\bcat\b'
text = "The cat is on the catwalk"
match = re.search(pattern, text)
print(match.group())  # 输出: cat

10.忽略大小写匹配

pattern = r'cat'
text = "The Cat is on the catwalk"
matches = re.findall(pattern, text, re.IGNORECASE)
print(matches)  # 输出: ['Cat', 'cat']

11.匹配多行文本

pattern = r'^cat'
text = "cat\nDog\ncat"
matches = re.findall(pattern, text, re.MULTILINE)
print(matches)  # 输出: ['cat', 'cat']

12.替换匹配项的函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图灵学者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值