Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a specific word from a string

Tags:

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?

like image 998
MiDo Basha Avatar asked May 19 '12 01:05

MiDo Basha


People also ask

How do you remove a specific word from a string in Python?

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.

How do you delete a specific word in a string in Java?

Remove Word from String in Java using Library Functionstr = str. replaceAll(word, "");

How do I remove a word from a string in C++?

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.


1 Answers

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).
like image 199
Hovercraft Full Of Eels Avatar answered Oct 11 '22 14:10

Hovercraft Full Of Eels