Python|Python中正则表达式的使用

P y t h o n Python Python中正则表达式的使用 r e . c o m p i l e ( ) re.compile() re.compile() 返回一个正则表达式的对象 ( p a t t e r n ) (pattern) (pattern),可用于 m a t c h , s e a r c h match,search match,search函数。
m a t c h , s e a r c h match,search match,search返回一个匹配对象 m a t c ho b j e c t match\ object match object
g r o u p s ( ) groups() groups()返回一个由字符串组成的元组。
g r o u p ( n u m = 0 ) group(num=0) group(num=0)若是一个参数则返回该位置对应的字符串,若为多个参数返回对应位置字符串组成的元组,若没有参数返回整个字符串。
s p a n ( n u m = 0 ) span(num=0) span(num=0)与 g r o u p ( ) group() group()类似,只不过该函数是返回对应字符串的开始位置 s s s,终止位置 t t t, [ s , t + 1 ) [s,t+1) [s,t+1)
Python|Python中正则表达式的使用
文章图片

r e . s u b ( p a t t e r n , r e p l , s t r i n g , c o u n t = 0 , f l a g s = 0 ) re.sub(pattern,repl,string,count=0,flags=0) re.sub(pattern,repl,string,count=0,flags=0)替换字符串的匹配项。
r e . f i n d a l l ( p a t t e r n , s t r i n g , f l a g s = 0 ) re.findall(pattern,string,flags=0) re.findall(pattern,string,flags=0)
返回一个由匹配到的所有子串组成的列表,若无匹配的,返回空列表。
r e . s p l i t ( p a t t e r n , s t r i n g [ , m a x s p l i t = 0 , f l a g s = 0 ] ) re.split(pattern,string[,maxsplit=0,flags=0]) re.split(pattern,string[,maxsplit=0,flags=0])
返回分割后的字符串列表。
Python|Python中正则表达式的使用
文章图片

常用的正则表达式语法:
\ w : \backslash w: \w:匹配数字字母下划线。
\ W : \backslash W: \W:匹配非(数字字母下划线)
\ d : \backslash d: \d:匹配数字
\ D : \backslash D: \D:匹配非数字
\ s : \backslash s: \s:匹配空白字符
【Python|Python中正则表达式的使用】 \ S : \backslash S: \S:匹配非空字符

    推荐阅读