[Python] Replace only some words using a regular expression

Discussão em 'Python' iniciado por Stack, Setembro 25, 2024.

  1. Stack

    Stack Membro Participativo

    I have a text with many "PROB TEMPO" and "TEMPO" words, and I want to insert a line break just before the word "PROB" or before the word "TEMPO" when PROB doesn´t appear before TEMPO. I am using Python with re.sub

    For example,

    text = "PROB TEMPO BKN001 TEMPO BKN009 PROB TEMPO BKN008 TEMPO BKN012..."
    new_text = re.sub("PROB TEMPO", "PROB </br>&emsp;TEMPO", text)
    new_text = re.sub("BKN009 TEMPO", "BKN009 </br>&emsp;TEMPO", text)
    new_text = re.sub("BKN012 TEMPO", "BKN012 </br>&emsp;TEMPO", text)


    The problem is that I have to check all the possibilities. Could I use regular expressions in re.sub? For example, I used this but it didn´t work

    new_text = re.sub("BKN0\d\d", "BKN0\d\d </br>&emsp;TEMPO", text)

    Continue reading...

Compartilhe esta Página