仅用python regexp替换字符的单个实例 [英] replacing only single instances of a character with python regexp

查看:30
本文介绍了仅用python regexp替换字符的单个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用其他东西替换单个 $ 字符,并且想连续忽略多个 $ 字符,但我不太明白如何做.我尝试使用前瞻:

s='$a $$b $$$c $d're.sub('\$(?!\$)','z',s)

这给了我:

'za $zb $$zc zd'

当我想要的是

'za $$b $$$c zd'

我做错了什么?

解决方案

注意,如果不使用可调用的替换函数:

  • 你需要先行,因为如果后面跟着$
  • ,你必须不匹配
  • 如果前面有 $
  • ,您将需要后视,因为您必须不匹配

不是那么优雅,但这是非常可读的:

<预><代码>>>>def Dollar_repl(matchobj):... val = matchobj.group(0)...如果 val == '$':... val = 'z'...返回值...>>>进口重新>>>s = '$a $$b $$$c $d'>>>re.sub('\$+', Dollar_repl, s)'za $$b $$$c zd'

I am trying to replace single $ characters with something else, and want to ignore multiple $ characters in a row, and I can't quite figure out how. I tried using lookahead:

s='$a $$b $$$c $d'
re.sub('\$(?!\$)','z',s)

This gives me:

'za $zb $$zc zd'

when what I want is

'za $$b $$$c zd'

What am I doing wrong?

解决方案

notes, if not using a callable for the replacement function:

  • you would need look-ahead because you must not match if followed by $
  • you would need look-behind because you must not match if preceded by $

not as elegant but this is very readable:

>>> def dollar_repl(matchobj):
...     val = matchobj.group(0)
...     if val == '$':
...         val = 'z'
...     return val
... 
>>> import re
>>> s = '$a $$b $$$c $d'
>>> re.sub('\$+', dollar_repl, s)
'za $$b $$$c zd'

这篇关于仅用python regexp替换字符的单个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆