2019年10月29日 星期二

python之正则sub函数split函数


文章轉自 https://blog.csdn.net/GrofChen/article/details/93598605

python之正则sub函数split函数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/GrofChen/article/details/93598605
re.sub函数用于将原字符串匹配的字符替换,替换的可以是字符串,也可以是函数
格式:re.sub(表达式,字符串,原字符串【,次数,标志位】)
import re
a = "1234567abcdefg"           # \D表示非数字字符
s = re.sub('\D.*', "890", a)   # \D.*即非数字字符开头的字符串
print(s)
  • 1
  • 2
  • 3
  • 4
在这里插入图片描述
def one(matched):            # 参数为匹配对象
    s =matched.group('num')  # 匹配的分组结果
    return s.zfill(3)        # 对结果进行填充
 
a ='a1b2c3d4e5f6'
print(re.sub('(?P<num>\d)', one, a,3)) # \d为数字字符
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
在这里插入图片描述
re.split函数用于将符串中匹配的字符分割为列表
格式:re.split(表达式,字符串【,次数,标志位】)
import re
a='i love chian'
print(re.split('\s', a))    # \s为空字符
print(re.split('(\s)',a))   # 空字符也分为一组
print(re.split('\s', a, 1)) # 分割次数为1
print(re.split('\d', a))    # 匹配不到时不分割
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
在这里插入图片描述

沒有留言:

張貼留言