Reputation: 143
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
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
def[^y]*y
: digit is not before def..y
[^y]*y
: digit is before ..y
Upvotes: 1
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