我在堆栈溢出上找到的所有示例对我来说都太复杂,无法进行反向工程
考虑这个玩具例子
s = "asdfasd a_b dsfd"
我想要s = "asdfasd a'b dsfd"
也就是说:找到由下划线分隔的两个字符,并用撇号替换该下划线
尝试:
re.sub("[a-z](_)[a-z]","'",s)
# "asdfasd ' dsfd"
我以为()
应该解决这个问题
更令人困惑的是,我们似乎成功地找到了要替换的角色:
re.findall("[a-z](_)[a-z]",s)
#['_']
为什么不更换这个
谢谢
Tags:
re.sub
将替换它匹配的所有内容有一种更通用的方法来解决您的问题,您不需要重新修改正则表达式
代码如下:
输出:
'Data: year=am_replace_str, monthday=am_replace_str, month=am_replace_str, some other text'
当然,如果您的案例不包含组,您的代码可能如下所示:
使用“向前看”和“向后看”模式:
“向前看/向后看”模式的宽度为零,因此不会替换任何内容
UPD:
re.sub
将替换整个匹配的表达式,包括前面和下面的字母李>re.findall
仍然匹配整个表达式,但它也有一个组(内括号),您观察到了这一组。整个比赛仍然是a_b
re.sub("([a-z])_([a-z])", r"\1'\2", s)
使用
re.sub
时,必须捕获要保留的文本,而不应捕获要删除的文本使用
见proof
解释
Python code:
输出:
相关问题 更多 >
编程相关推荐