Python中正则表达式的使用

PythonPython中正则表达式的使用

re.compile()re.compile() 返回一个正则表达式的对象(pattern)(pattern),可用于match,searchmatch,search函数。
match,searchmatch,search返回一个匹配对象match objectmatch\ object

groups()groups()返回一个由字符串组成的元组。

group(num=0)group(num=0)若是一个参数则返回该位置对应的字符串,若为多个参数返回对应位置字符串组成的元组,若没有参数返回整个字符串。

span(num=0)span(num=0)group()group()类似,只不过该函数是返回对应字符串的开始位置ss,终止位置tt,[s,t+1)[s,t+1)
Python中正则表达式的使用
re.sub(pattern,repl,string,count=0,flags=0)re.sub(pattern,repl,string,count=0,flags=0)替换字符串的匹配项。

re.findall(pattern,string,flags=0)re.findall(pattern,string,flags=0)

返回一个由匹配到的所有子串组成的列表,若无匹配的,返回空列表。

re.split(pattern,string[,maxsplit=0,flags=0])re.split(pattern,string[,maxsplit=0,flags=0])

返回分割后的字符串列表。

Python中正则表达式的使用
常用的正则表达式语法:

\w:\backslash w:匹配数字字母下划线。

\W:\backslash W:匹配非(数字字母下划线)

\d:\backslash d:匹配数字

\D:\backslash D:匹配非数字

\s:\backslash s:匹配空白字符

\S:\backslash S:匹配非空字符