正则表达式

基本用法

. 匹配换行符外的任意字符

\w 匹配字母、数字、下划线、汉字 \W 匹配非字母、数字、下划线、汉字
\s 匹配任意空白符 \S 匹配除单个字符外的所有字符(包括tal和换行符)
\d 匹配数字 \D 匹配非数字
\b 匹配单词边界
() 分组
^ 匹配字符串开始 $匹配字符串结束
\A 匹配字符串开始 \Z匹配字符串结束

?0次或多次

+1次或多次

*0次或多次

{n} n次
{n,} 最少n次
{n,m} n次到m次

| 表示或

转义 \

[^ ] 排除匹配


贪婪匹配 .*
非贪婪匹配 .*?


匹配汉字 [\u4e00-\u9fa5]
匹配英文字母 [a-zA-Z] 含大小写
匹配英文字母和数字组合 [a-zA-Z0-9]

python中的正则表达式

  • findall
import re

#正则
pattern = r"https://.*?.com"

#str字符串
txt = "https://www.baidu.com/ sdfsdfsdfdsfsdfsdf sdfdsf https://www.bilibili.com/"

#匹配
match = re.findall(pattern, txt)

#打印
print(match)

结果
['https://www.baidu.com', 'https://www.bilibili.com']
  • search和group
import re

# 要匹配的字符串
input_string = "17353190891"

# 定义正则表达式模式,匹配11位数字,并提取第4位到第8位的数字
pattern = r"\d{3}(\d{5})\d{3}"

# 使用re.search()函数进行匹配
match = re.search(pattern, string)

# 如果匹配成功
if match:
# 提取第4位到第8位的数字
extracted_digits = match.group(1) #第一个()的内容
print("提取的数字:", extracted_digits)
else:
print("没有找到匹配的数字")

结果
提取的数字: 53190