regex for replace the beginning of each word in the sentence

Viewed 37

I want to replace the beginning of each word in a sentence if the beginning matches string x, regardless of uppercase lowercase.

For example: s = "My fAther is your grandFAther and Family is important"

replacing "FA" with "zZ" in the beginning of each word in the sentence results in "My zZther is your grandFAther and zZamily is important".

A regex would be very helpful, but if you can't, other code would be ok. I honestly can't find an effective solution.

Also, if you can give me a regex for when you want to replace the word termination, it would be very nice. eg: "green blablaen enenbla" -> "grezz blablazz enenbla".

thank you very much :D!

my code:

    input: s, value_to_replace, new_value 
        w = s.split()
        for i in range(len(w)):
            w[i] = re.sub(pattern='^' + value_to_replace, repl=new_value, string=w[i],flags=re.IGNORECASE)
    return ' '.join(w)

But idk if this is efficient, it can somehow make a regex that applies over all the sentence, not over a separate word.

1 Answers

Give this a shot, I think it'll get you want you want

import re

def main():
    text = "My father is your grandFAther and family is important"
    text = re.sub(r"\bfa", "zZ", text, flags=re.IGNORECASE)
    print (text)

    term_text = "green blablaen enenbla"
    term_text = re.sub(r"\w{2}\b", "zz", term_text, flags=re.IGNORECASE)
    print(term_text)    

if __name__ == "__main__":
    main()
My zZther is your grandFAther and zZmily is important
grezz blablazz enenbzz

You can certainly iterate/loop by splitting the sentence, but this is probably the direction you want to go in.

What we are taking advantage of is word boundaries (the \b). The \w is a character class (A-Z0-9_) and the {2} is number of characters to its immediate left. You can read more word boundaries here, they are extremely powerful! :) https://www.regular-expressions.info/wordboundaries.html

note: nice update/edit to your question :)

Related