python如何使用正则表达式

2025-10-26 22:13:05

1、match(pattern, string[, flag=0])函数

Pattern:正则表达式

String:待匹配的字符串

Flags:可选参数,表示是否区分大小写、多行匹配等

如果匹配,返回匹配到的第一个对象,否则None

m.groups()列出所有正则的匹配项

m.group(0), m.group(1),……取出第一个、第二个……匹配的子串

python如何使用正则表达式

python如何使用正则表达式

2、search(pattern, string[, flag=0])函数

Pattern等参数和match一样

如果搜索到匹配的子串,则返回匹配到的第一个对象,否则返回None

python如何使用正则表达式

python如何使用正则表达式

3、sub(pattern, sub, string, count函数

Pattern:正则表达式

Sub:要替换到字符串中去的部分

String:待替换的字符串

Count:替换多少个。默认是找到几个就替换几个

返回string在执行之后的结果。如果没有找到可以被替换的子字符串,也依旧返回原字符串

python如何使用正则表达式

python如何使用正则表达式

4、split(pattern, string)函数

Pattern:正则表达式

String:待切割的字符串

返回一个列表,这个列表由被切割出来的子串组成。如果找不到作为分割点的字符,则返回整个字符串

python如何使用正则表达式

python如何使用正则表达式

5、findall(pattern, string)函数

Pattern:正则表达式

String:待查找的字符串

函数将所有满足条件的子字符串找出之后,放入一个列表并返回之。

python如何使用正则表达式

python如何使用正则表达式

6、compile(pattern[,flags=0])函数

说明同match参数

预编译,加快速度。返回一个regex对象,用法和re一样,只不过是不再需要输入pattern

python如何使用正则表达式

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢