Search code examples
pythonregexpython-3.xstringregex-group

Trying to replace the Specific word with another word but i didn't get exact result. Is there any resolution using regex?


I Want to replace the 'REF ' tag to 'REF:'.

Please check the below code:-

def test():
    str_data = "REF PUNE UNIVERCITY BMS:KOLHAPUR UNIVERSITY REF NO : MUMBAI UNIVERSITY"
    tag_list = ["REF ", "BMS:", "REF NO :"]
    for each_value in tag_list:
        if each_value[-1] == " ":
            print(each_value)
            str_data = str_data.replace(each_value, each_value[:-1] + ":")
            print(str_data)

test()

I tried to solve it but I got the below output.

Original String = "REF PUNE UNIVERCITY BMS:KOLHAPUR UNIVERSITY REF NO : MUMBAI UNIVERSITY"

My Result = REF:PUNE UNIVERCITY BMS:KOLHAPUR UNIVERSITY REF:NO : MUMBAI UNIVERSITY

Expected Result = REF:PUNE UNIVERCITY BMS:KOLHAPUR UNIVERSITY REF NO : MUMBAI UNIVERSITY

Is there any way to resolve it? Is there any regex expression?


Solution

  • With a regular expression it's easy to say "match "REF " but only if it is not followed by "NO :"":

    import re
    
    str_data = re.sub(r'REF (?!NO :)', 'REF:', str_data)
    

    The negative lookahead (?!NO :) means if the text at this point matches NO :, do not match.