threefourfour

 

正则匹配re

1.特殊语法:

  \d:匹配数字    \w:匹配字母/数字/下划线  \s:匹配空白字符

  *:0次或多次  +:1次或多次  ?:0次或多次

  ^:匹配开头  $:匹配结尾

2.常用函数:

(1)re.search(pattern, string)

功能:在字符串中搜素第一个匹配项

示例:

import re
text = "Hello, 我的电话是123-4567,邮箱是user@example.com"
match = re.search(r'\d{3}-\d{4}', text)  # 查找电话号码
if match:
    print("找到电话:", match.group())  # 输出:123-4567

(2)re.match(pattern, string)

功能:仅从字符串开头匹配,若开头不匹配则返回None

示例:

result = re.match(r'Hello', text)  # 检查是否以 "Hello" 开头

(3)

re.findall(pattern, string)

功能:返回所有匹配项的列表

示例:

emails = re.findall(r'\w+@\w+\.\w+', text)
print(emails)  # 输出:['user@example.com']

(4)

re.split(pattern,string)

功能:按正则表达式分割字符串

示例:

parts = re.split(r'[,\s]+', "a,b  c   d")  # 按逗号或空格分割
print(parts)  # 输出:['a', 'b', 'c', 'd']

(5)

re.sub(pattern, repl, string)

功能:替换所有匹配项

示例:

new_text = re.sub(r'\d{3}-\d{4}', '***-****', text)
print(new_text)  # 将电话号码替换为 ***-****

 

 

  

posted on 2025-04-13 22:05  肆叁叁  阅读(15)  评论(0)    收藏  举报

导航