2

I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.

For example, for the below string I only want to replace x with y in z string. how to do that?

x = "112-224"
y = "hello"
z = "This is the number 112-224 not #112-224"

When I do re.sub(r'\b' + x + r'\b', y, z) I am getting 'This is the number hello not #hello'. So basically doesn't work with this regex. I am really not good with this regex stuff. What's the right way to do that? so, i can get This is the number hello not #112-224.

2 Answers 2

3

How about this:

pattern = r'(?<=[\w\s\n\r\^])'+x+r'(?=[\w\s\n\r$])'

With the complete code being:

x = "112-234"
y = "hello"
z = "112-234this is 112-234 not #112-234"

pattern = r'(?<=[\w\s\n\r\^])'+x+r'(?=[\w\s\n\r$])'

Here, I'm using a positive lookbehind and a positive lookahead in regex, which you can learn more about here

The regex states the match should be preceded by a word character, space, newline or the start of the line, and should be followed by a space, word character newline or the end of the line.

Note: Don't forget to escape out the carat ^ in the lookbehind, otherwise you'll end up negating everything in the square brackets.

1
  • No problem, glad I could be of help :)
    – Robo Mop
    Commented Feb 15, 2020 at 11:47
1

Using a lookahead:

re.sub("\d{3}-\d{3}(?=\s)",y,z)
'This is the number hello not #112-224'

The above assumes that the digits will always be at most three.

Alternatively:

re.sub("\d.*\d(?=\s)","hello",z)
'This is the number hello not #112-224'
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.