re 模块

re 模块

 

\w  字母数字下划线

\s  所有不可见字符

\d  所有数字

.   所有字符(除了换行符)

\b  单词末尾

 

^  行首

$  行尾

 

+  1个或多个

*  0个或多个

 

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

{m} 必须是m 次不能多不能少

{n} 最大n

 

[abc]   a|b|c   范围匹配

 

() 分组优先括号里面的

?: 取消括号优先级 

 

 

re模块常用方法
findall 从左往右查找所有满足条件的字符 返回一个列表

search 返回第一个匹配的字符串 结果封装为对象 span=(0, 5) 匹配的位置 match匹配的值
match     匹配行首  返回值与search相同

  对于search match 匹配的结果通过group来获取
compile  将正则表达式 封装为一个正则对象 好处是可以重复使用这个表达式

 

 


findall   查找所有的

search    查找索引    从左到右一次匹配返回第一次匹配的结果

print(re.search("hello"," world hello python"))

 

match     只查行首索引

print(re.match("hello"," world hello python"))     没有则为None

 

split     切割

print(re.split("hello","world hello python",maxsplit=0))

 

sub      替换

src = "c++|java|python|shell"
# 用正则表达式将c shell换位置
print(re.sub("([a-zA-Z]+)|","",src))




 

posted @ 2018-08-14 17:09  星牧  阅读(89)  评论(0编辑  收藏  举报