Dnaiel
Dnaiel

Reputation: 7832

replace word using regex with specific conditions

How would I use the python "re" module to replace a word, i.e., 'co' with an empty string, i.e., '' in a given text, only if:

I.e.,

# word is not the final word in the text but there's a space at beginning, and then another space at the end of the word
txt = 'A co is mine'
txt_after_replace = 'A is mine'
txt = 'A column is mine'
txt_ater_replace = 'A column is mine'
# word is the end of the text and there's a space before the word
txt = 'my co'
txt_after_replace = 'my'
txt = 'my column'
txt_after_replace = 'my column'

If I do: txt.replace(' co', '') these two cases will fail: txt = 'my column', txt_ater_replace = 'A column is mine'. Since it won't check for the end of text right after the word or for a space in the text right after the word.

I think the re.sub module would come to the rescue here but I'm unsure how.

This should work for any general word, i.e., 'co' in this case.

Upvotes: 0

Views: 625

Answers (2)

Skycc
Skycc

Reputation: 3555

you can use lookahead regex

\sco(?=$|\s)

explanation:

  • space follow by co, then assert what follow by co must be either space or end of text

python code

import re
txt = 'A co is mine, A column is mine, my column, my co'
new_txt = re.sub('\sco(?=$|\s)', '', txt)
# 'A is mine, A column is mine, my column, my'

Upvotes: 0

Rahul
Rahul

Reputation: 2738

You can use alternation to match both criteria using following regex.

Regex: (?:\sco\s|\sco$)

Explanation:

  • \sco\s matches co preceded and succeed by a space.

  • \sco$ matches co at end preceded by a space.

Regex101 Demo

In python:

import re
str = "coworker in my company are not so co operative. silly co"
res = re.sub(r'(?:\sco\s|\sco$)', ' ', str)
print(res)

Result: coworker in my company are not so operative. silly

Ideone Demo

Upvotes: 1

Related Questions