Replace only some words using a regular expression [closed]

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> TEMPO", text)
new_text = re.sub("BKN009 TEMPO", "BKN009 </br> TEMPO", text)
new_text = re.sub("BKN012 TEMPO", "BKN012 </br> 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("BKN0dd", "BKN0dd </br> TEMPO", text)

New contributor

nico is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

5

Try matching:

((?:bPROB )?TEMPOb)

and replacing:

n1

See: regex101

Python code see online python:

# import the re module
import re

s="PROB TEMPO BKN001 TEMPO BKN009 PROB TEMPO BKN008 TEMPO BKN012"

# match and substitution pattern
mPattern=r"((?:bPROB )?TEMPOb)"
sPattern=r"n1"

# substitution; notice thta `.lstrip()` removes the leading `n`.
# dont know if thats desired. else just delete
res=re.sub(mPattern,sPattern,s).lstrip()

# result
print(res)

Outputs:

PROB TEMPO BKN001 
TEMPO BKN009 
PROB TEMPO BKN008 
TEMPO BKN012

Explanation

match:

  • (): capture to group 1
  • (?:bPROB )?: maybe preceeded with word PROB
  • TEMPOb: the word TEMPO

replace:

  • n1: linebreak and matched

1

You can use

import re

text = "PROB TEMPO BKN001 TEMPO BKN009 PROB TEMPO BKN008 TEMPO BKN012..."
print( re.sub(r"b(?!^)(PROBs+TEMPO|(?<!PROBs)TEMPO)bs*", "n\g<0>", text) )

See the Python demo and the regex demo. Output:

PROB TEMPO BKN001 
TEMPO BKN009 
PROB TEMPO BKN008 
TEMPO BKN012...

The b(?!^)(PROBs+TEMPO|(?<!PROBs)TEMPO)bs* regex matches any PROB TEMPO or TEMPO (not immediately preceded with PROB and a whitespace) a whole words.

If you need to support more than one whitespace before TEMPO, you’d need to intall PyPi regex module and then import regex as re and use b(?!^)(PROBs+TEMPO|(?<!PROBs+)TEMPO)bs*.

2

Although OP is asking about how to use RE for this it’s not clear if RE is actually a requirement. Why not use a simple loop?

text = "PROB TEMPO BKN001 TEMPO BKN009 PROB TEMPO BKN008 TEMPO BKN012"

p, *tokens = text.split()

result = p

for t in tokens:
    if t == "PROB" or (t == "TEMPO" and p != "PROB"):
        result += r"<br> "
    else:
        result += " "
    result += (p := t)

print(result)

Output:

PROB TEMPO BKN001<br> TEMPO BKN009<br> PROB TEMPO BKN008<br> TEMPO BKN012

Note:

Although not specifically stated in the OP, my guess is that br would not be required at the start of the output string.

This implementation for the relatively small input string is significantly faster than a RE solution

There are two ways to solve your problem.
One is to simply substitute both patterns “PROB” and “TEMPO” (not preceded by “PROB”) in turn:

import re

text = "PROB TEMPO BKN001 TEMPO BKN009 PROB TEMPO BKN008 TEMPO BKN012..."

new_text = re.sub(r"PROB", r"<br/> PROB", text)
new_text = re.sub(r"(?<!PROB) TEMPO", r"<br/> TEMPO", new_text)
print(new_text)

Will print:

<br/> PROB TEMPO BKN001<br/> TEMPO BKN009 <br/> PROB TEMPO BKN008<br/> TEMPO BKN012...

The (?<!PROB) part is a negative lookbehind as explained in the documentation and will match something not preceded by “PROB”.

The other solution uses two more regex tools: the or operator and backreferences and is a bit more elegant from the regex point of view.

import re

text = "PROB TEMPO BKN001 TEMPO BKN009 PROB TEMPO BKN008 TEMPO BKN012..."

new_text = re.sub(r"PROB|(?<!PROB) TEMPO", r"<br/> g<0>", text)
print(new_text)

Will print:

<br/> PROB TEMPO BKN001<br/>  TEMPO BKN009 <br/> PROB TEMPO BKN008<br/>  TEMPO BKN012...

The pattern to match is “PROB” OR “TEMPO” (not preceded by “PROB”).
The g<0> in the replacement string is a backreference to the entire match.

In your question, you attempted to use a backreference with started your replacement string with BKN0dd.
The intention is obvious but this will only resolve to literal backspace-d’s.
Backreferences tell the regex engine “that’s what a previous pattern matched”.

Also note that I used <br/> (not </br>) as this is the correct XHTML element for a line break.
This assumes your string is somehow used in an HTML document.
Wiktor’s answer demonstrates how to add actual line breaks.

10

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật