How to replace a word with new word in string using regex in java?

Member

by dedrick , in category: Third Party Scripts , 5 months ago

How to replace a word with new word in string using regex in java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 5 months ago

@dedrick 

You can replace a word with a new word in a string using regex in Java by using the replaceAll() method of the String class. Here's an example:

1
2
3
String str = "This is a sample sentence.";
String newStr = str.replaceAll("\b(sample)\b", "replacement");
System.out.println(newStr);


In this example, we are replacing the word "sample" in the original string with the word "replacement". The \b in the regex pattern is used to match word boundaries, ensuring that only the word "sample" is replaced and not any other word that contains "sample" as a substring.


You can modify the regex pattern and replacement word as needed for your specific use case.

Related Threads:

How to set max limit for each word in the sentence using regex in java?
How to find repeated word in a string with regex?
How to delete a word in a column using regex?
How to get the second part of a hyphenated word using regex?
How to replace string before string using regex?
How to exclude a word with regex?