Jitendra Aswani
Jitendra Aswani

Reputation: 143

Replace numbers between parts of string using regex

I want to replace numbers between some part of string

for eg :.

f = "abc 123 def 23435 kill x22 y2986" 

I want to replace all umber between def and y with #

Tried using the following expression , it didnt work

exp = re.sub(r"(?<=def)\d+(?=y)", "#", f)

Expected output :

abc 123 def ##### kill x## y2986

Upvotes: 1

Views: 82

Answers (2)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

in the general case it is not possible without a variable length lookbehind, however in that particular case it can be done with a positive and a negative lookahead however it may replace digit if there is another y after last y :

\d(?!.*def[^y]*y)(?=[^y]*y)

matches a digit

  • which is not followed by def[^y]*y : digit is not before def..y
  • and is followed by [^y]*y : digit is before ..y

check here regex101

Upvotes: 1

riteshtch
riteshtch

Reputation: 8769

Well, I think at first glance it seems it is difficult to do it with regex but there is a way to do it by applying regex in multiple levels (in this case 2 levels). Here is an example:

>>> f = "abc 123 def 23435 kill x22 y2986" 
>>> import re
>>> exp = re.sub(r"(?<=def)(.*)(?=y)", lambda x:re.sub(r"\d", '#', x.group()), f)
>>> exp
'abc 123 def ##### kill x## y2986'
>>> 

Upvotes: 4

Related Questions