I'm trying to remove a specific word from a certain string using the function replace()
or replaceAll()
but these remove all the occurrences of this word even if it's part of another word!
Example:
String content = "is not like is, but mistakes are common"; content = content.replace("is", "");
output: "not like , but mtakes are common"
desired output: "not like , but mistakes are common"
How can I substitute only whole words from a string?
text = input('Enter a string: ') words = text. split() data = input('Enter a word to delete: ') status = False for word in words: if word == data: words. remove(word) status = True if status: text = ' '. join(words) print('String after deletion:',text) else: print('Word not present in string.
Remove Word from String in Java using Library Functionstr = str. replaceAll(word, "");
Remove a Given Word from a String using C++Find the word in the matrix and replace that row with the null character where the word. Finally, print the reordered string.
What the heck,
String regex = "\\s*\\bis\\b\\s*"; content = content.replaceAll(regex, "");
Remember you need to use replaceAll(...)
to use regular expressions, not replace(...)
\\b
gives you the word boundaries\\s*
sops up any white space on either side of the word being removed (if you want to remove this too).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With