0

I am having difficulties replacing exact insensitive match of a string without affecting bigger strings having part of the string of interest.

What I mean is: if I have a string "INFO", I want to replace it with "INFORMATION" and if for instance I find a string "INFOR" I do not want to do anything because it is not exact match of "INFO".

I did this in python:

string = re.compile(re.escape("info"), re.IGNORECASE)
string = string.sub("information", "This might be related to info disclosure. Because Infor disclosure....")
print(string)

I am getting as output:

This might be related to information disclosure. Because informationr disclosure....

which is not what I want because infor is being replaced by informationr

Any way to solve this?

c1377554
  • 173
  • 1
  • 10
  • You can add spaces around the match, or you can match against `info([^r])` and then just replace with information + matched group – Artog Nov 04 '19 at 11:46
  • works with spaces as you suggested, but then one cannot rely on it. Let's say I have "info." with full stop and not spaces and I still want "info." to be "information." .... – c1377554 Nov 04 '19 at 12:00
  • 1
    Use word boundary as: `string = re.compile(r'\binfo\b', re.IGNORECASE)` – anubhava Nov 04 '19 at 12:03
  • 1
    @anubhava, thanks that works. If you add as answer I accept it. Thanks :) – c1377554 Nov 04 '19 at 12:06

1 Answers1

0

Regular expressions will solve your problem. you can use re library and you should just put space before and after "info":

import re
string = re.compile(re.escape(" info "), re.IGNORECASE)
string = string.sub(" information ", "This might be related to iNfo disclosure. Because Infor disclosure....")
print(string)
Benyamin Karimi
  • 133
  • 1
  • 1
  • 9
  • 1
    This solution would fail when info has no space... for instance ".info." or "bla_bla\info" or "info." @anubhava commented on the post to add word boundary in the re.compile, that solves the problem for all cases. – c1377554 Nov 04 '19 at 12:29