How to replace all occurrences by regex?

Member

by lottie , in category: Third Party Scripts , 6 days ago

How to replace all occurrences by regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 5 days ago

@lottie 

You can use the replaceAll() method in Java to replace all occurrences of a pattern using regex. Here's an example:

1
2
3
4
5
6
7
String input = "Hello, World! Hello, Universe!";
String pattern = "Hello";
String replacement = "Hi";

String output = input.replaceAll(pattern, replacement);

System.out.println(output);


Output:

1
Hi, World! Hi, Universe!


In this example, we are replacing all occurrences of the word "Hello" with "Hi" in the input string. You can customize the regex pattern to match any specific pattern or expression that you want to replace.