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

Member

by dedrick , in category: Third Party Scripts , 12 days 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 , 11 days 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.