Python正则匹配函数re.sub()

问题描述

利用re.sub()完成字符串匹配和切割任务,如:
输入:

  1. 由AGCT组成的DNA序列(字符串)s,如:‘GCATAGTAATGTATTAATGGC’
  2. 切割酶的切割pattern, 并使用"|“表示切割,如” A.T|AAT”

输出:
切割结果,如 [GCATAGT; AATGTATT; AATGGC]

求解

使用下面一行代码即可求解:

re.sub(pattern, r'\1:\2' s).split(':')

原理

根据如下代码和注释理解re.sub即可。

import re
pattern = r'(.*)cat(.*)aa'
# 匹配到了2个分组
# 输出:把text中被匹配到的部分替换为replacement_template中的内容
replacement_template = r'\2cat\1' # dogcatllama => llamacatdog
replacement_template = r'\1cat\2' # dogcatllama => dogcatllama
replacement_template = r'\2' # dogcatllama => dog
text = 'dogcatllama'
new_text = re.sub(pattern, replacement_template, text) # 将所有pattern匹配项用replacement替换
print(text, '=>', new_text)

# 1. 对于分组的匹配,找到的匹配结果是什么? pattern = r'(.*)cat(.*)'
# 2. re.sub的用法

# more example:
# ======== E1 ==============
phone = "2004-959-559 # 这是一个电话号码"
 
# 删除注释
num = re.sub(r'#.*$', "", phone)
print ("电话号码 : ", num)
 
# 移除非数字的内容
num = re.sub(r'\D', "", phone)
print ("电话号码 : ", num)

# ======== E2 ==============
pattern = '[0-9]+'
string = 'Account Number - 12345, Amount - 586.32'
repl = 'NN'

print('Original string')
print(string)

result = re.sub(pattern, repl, string)

print('After replacement')
print(result)

# Original string
# Account Number - 12345, Amount - 586.32
# After replacement
# Account Number - NN, Amount - NN.NN

# ======== E3 ==============
pattern = '[0-9]+'
string = 'Account Number - 12345, Amount - 586.32'
repl = 'NN'

print('Original string')
print(string)

result = re.sub(pattern, repl, string, count=2)

print('After replacement')
print(result)

# Account Number - 12345, Amount - 586.32
# After replacement
# Account Number - NN, Amount - NN.32


# ========= E4 ====================
pattern = '[a-z]+'
string = 'Account Number - 12345, Amount - 586.32'
repl = 'AA'

print('Original string')
print(string)

result = re.sub(pattern, repl, string, flags=re.IGNORECASE)

print('After replacement')
print(result)

# Original string
# Account Number - 12345, Amount - 586.32
# After replacement
# AA AA - 12345, AA - 586.32
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

R.X. NLOS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值