Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

regex - replacing only single instances of a character with python regexp

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...