How to use \b or ^ alongwith pattern to replace complete word?

I am trying to use regex for replacement of words, but instead of complete words even words in between sentences are getting replaced.

prepos = ['has','had','have','is','you']
prepo = re.compile('|'.join(prepos))

# x["text"] - contains text with sentences in english

twete = re.sub(prepo,' ',x["text"])
print(twete)

output: replaces subwords as well i want to subsitute complete word ocurrences only. How can I use ^ or \b in this case?

Answers


import re
p = re.compile(r"\b(foo|bar|baz)\b")
p.sub("---", "foo XfooX bar YbarY baz ZbazZ")
# => '--- XfooX --- YbarY --- ZbazZ'

Edit:

If you want to join the regex:

prepos = ["foo", "bar", "baz"]
p = re.compile(r"\b(" + "|".join(prepos) + r")\b")
p.sub("---", "foo XfooX bar YbarY baz ZbazZ")
# => '--- XfooX --- YbarY --- ZbazZ'

Need Your Help

LWJGL Mouse scroll wheel getDWheel() Method

java input lwjgl mousewheel

I use the getDWheel method in my game like so:

How to get size of desktop exclusive of “System Tray”in Swing

java swing

How would I calculate the size of the desktop, exclusive of the System Tray, in Swing? I want to size my app's frame to fill that size. Toolkit.getScreenSize() returns the size including the system

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.