How to add a if condition in re.sub in python

How to add a if condition in re.sub in python

I am using the following code to replace the strings in words with words[0] in the given sentences.

I am using the following code to replace the strings in words with words[0] in the given sentences.

import re
sentences = ['industrial text minings', 'i love advanced data minings and text mining']

words = ["data mining", "advanced data mining", "data minings", "text mining"]

start_terms = sorted(words, key=lambda x: len(x), reverse=True) start_re = "|".join(re.escape(item) for item in start_terms)

results = []

for sentence in sentences:
for terms in words:
    if terms in sentence:
        result = re.sub(start_re, words[0], sentence)
        results.append(result)
        break

print(results)

My expected output is as follows:

[industrial text minings', 'i love data mining and data mining]

However, what I am getting is:

[industrial data minings', 'i love data mining and data mining]

In the first sentence text minings is not in words. However, it contains "text mining" in the words list, so the condition "text mining" in "industrial text minings" becomes True. Then post replacement, it "text mining" becomes "data mining", with the 's' character staying at the same place. I want to avoid such situations.

Therefore, I am wondering if there is a way to use if condition in re.sub to see if the next character is a space or not. If a space, do the replacement, else do not do it.

I am also happy with other solutions that could resolve my issue.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

An Introduction to Regex in Python

An Introduction to Regex in Python

The Ultimate Guide to Regex (Regular Expressions) in Python

In this Python tutorial, we’ll learning about Regex (Regular Expressions) in Python. Learn how Python regex works, and be able to use the basic patterns and functions in Python’s regex module, re, for to analyze text strings.