0

I need to replace a particular word abc with abc_test, but with \b, . is considered as word boundary so I get unexpected result. Can someone help me figure out how can I skip replacement for . with /b?

This is my script:

import re
f = open("4.txt", "r").read()
op = re.sub(r'\babc\b', 'abc_test', f)
print(op)

This is my input file 4.txt:

abc
abc xyz
abc
abc.asd

Output:

abc_test
abc_test xyz
abc_ztx
abc_test.asd # This gets replaced which is not as expected

Expected output:

abc_test
abc_test xyz
abc_ztx
abc.asd # This shouldn't be replaced

How can I restrict the regex to skip abc.asd here?

Sweety
  • 301
  • 1
  • 9
  • 1
    `\b` is a word boundary and there is a word boundary between `abc` and `.`. The question is, **why** is it not expected? If you just want to avoid matching before a `.`, use `r'\babc\b(?!\.)'` – Wiktor Stribiżew Mar 25 '21 at 18:41
  • Yes, that is what I was missing, thank you for pointing it out! If you can post this as an answer, I will accept it as the correct answer. – Sweety Mar 25 '21 at 18:43
  • It appears I have already answered a question explaining this trick. – Wiktor Stribiżew Mar 25 '21 at 18:48

0 Answers0