re正则表达式公式讲解4

1.re,split()  字符串分离

import re

s = "abc20tyu9iou16hij25"

m = re.split("\d",s)      #以"\d"来进行分割。
print(m)            # ['abc', '', 'tyu', 'iou', '', 'hij', '', ''] 结果有很多空格,为什么?ans:因为匹配到一个数字就停下来进行分离,第二个数字就变成了空格

m = re.split("\d+",s)
print(m)            # ['abc', 'tyu', 'iou', 'hij', '']结尾还有个空格为什么?因为末尾有个25,25后面没东西,但是25还是要分离一次。
import re

s = "abc20t%yu9iou16#hij25"


m = re.split("\d+|#|%",s)
print(m)               # ['abc', 't', 'yu', 'iou', '', 'hij', ''] #iou后面跟着个空格是因为16后面跟这个#,所以就多了个空格。

 

2.转义字符的用法

s = "abc20t%yu9|iou16#hij25"


# m = re.split("\|",s)                # ['abc20t%yu9', 'iou16#hij25']
# print(m)
# m = re.split("\\\\",s)          #分割路径
# print(m)                                # ['abc20t%yu9|iou16#h', 'ij25']

  

3.re.sub()  替换

import re

s = "abc20t%yu9|iou16#hij25"

m = re.sub("\d+","_",s)
print(m)                    # abc_t%yu_|iou_#hij_

m = re.sub("\d+","_",s,count = 2)       # count = 2 ,前两个替换
print(m)                    # abc_t%yu_|iou16#hij25 

  

4.maxsplit() 最大分割次数

import re

s = "1 + 2 -5*3 + 22/2"

m = re.split("[-+\*/]",s)           # ['1 ', ' 2 ', '5', '3 ', ' 22', '2']
print(m)

m = re.split("[-+\*/]",s,maxsplit = 3)  # maxsplit 最大分割次数
print(m)                             # ['1 ', ' 2 ', '5', '3 + 22/2']

  

  

  

posted @ 2018-04-20 23:33  Roc_Atlantis  阅读(303)  评论(0编辑  收藏  举报