python--正则match_compile_search_findall用法

时间:2022-06-24 04:14:03

正则表达式功能很强大,但学精通还是要自己花点时间的。

 

下面讲解下matchcompilesearchfindall常用的方法

 

  • Match

从字符串的第一个字符开始匹配,如果未匹配到返回None,匹配到则返回一个对象

python--正则match_compile_search_findall用法

未匹配到返回None

 

python--正则match_compile_search_findall用法

开始字符匹配到了h,在返回一个对象,并且需要通过group来获取这个h值。

 

  • Search

Searchmatch有些类似,只是搜索整个字符串然后第一个匹配到指定的字符则返回值,未匹配到则返回None。获取值得方法也需要通过group()

python--正则match_compile_search_findall用法

未匹配到字符则返回None

 

python--正则match_compile_search_findall用法

从字符串开始往后匹配,一匹配到则返回一个对象。需要通过group来获取匹配到的值。

 

  • Findall

Findall是匹配出字符串中所有跟指定值有关的值,并且以列表的形式返回。未匹配到则返回一个空的列表。

python--正则match_compile_search_findall用法

未匹配到返回一个空列表。

 

 

python--正则match_compile_search_findall用法

匹配出指定字符的所有值,并以列表返回值。

 

  • Compile

re.compile是将正则表达式转换为模式对象,这样可以更有效率匹配。使用compile转换一次之后,以后每次使用模式时就不用进行转换

python--正则match_compile_search_findall用法

其实这跟执行re.findall(‘img’,a)得到的结果是一样的,只是使用了compile后,下面执行findall方法时就不需要再转换一次模式对象了。


本文出自 “IT虫” 博客,请务必保留此出处http://laomomo.blog.51cto.com/6595318/1947243