Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a part of string in re.findall() result

In the below input string i want to replace the "item" with "replaced_item" based on the regex search condition.

re.findall(r"(\bsee\b|\bunder\b|\bin\b|\bof\b|\bwith\b|\bthis\b)( *.{0,4})(item)","i have many roof item in the repeat item of the item inthe item downunder. with any item")

gives output:

 [('of', ' the ', 'item'), ('with', ' any ', 'item')]

I want to replace the "item" keyword in the above matched phrases to "replaced_items".

Expected output: i have many roof item in the repeat item of the replaced_item inthe item downunder. with any replaced_item
like image 972
Apoorv Avatar asked Oct 30 '25 13:10

Apoorv


1 Answers

You may get the expected output with a \1\2replaced_item replacement string:

import re
pat = r"\b(see|under|in|of|with|this)\b( *.{0,4})(item)"
s = "i have many roof item in the repeat item of the item inthe item downunder. with any item"
res = re.sub(pat, r"\1\2replaced_item", s)
print(res)

See the Python demo

Also, note how word boundaries are now restricting the context for the words inside the alternation (since they are moved out, only 1 word boundary is required at both ends).

Just a note: if replaced_item is a placeholder, and can start with a digit, you should use r'\1\g<2>replace_item'. The \g<2> is an unambiguous backreference notation, see python re.sub group: number after \number SO post.

like image 128
Wiktor Stribiżew Avatar answered Nov 02 '25 13:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!