1

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
6
  • That regex matches "def, followed immediately by a digit sequence, followed immediately by a y". Your string has things other than digit sequences between "def" and "y", so it doesn't match. Commented Jan 19, 2018 at 16:14
  • So what is the way to do it Commented Jan 19, 2018 at 16:15
  • Looping is one. Commented Jan 19, 2018 at 16:16
  • But isnt there any way that regex can be applied between some words Commented Jan 19, 2018 at 16:18
  • 1
    What luck! @JitendraAswani, check out ritesht93's answer. Commented Jan 19, 2018 at 16:20

2 Answers 2

4

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'
>>> 
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

reread my answer ;), it is explained it works only for the case in the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.