![]() |
VOOZH | about |
Regular Expressions (regex), in Java, are a tool, for searching, matching, and manipulating text patterns. Regex patterns are usually written as fixed strings. Based on different scenarios we may need to create a regex pattern based on a given string.
In this article, we will learn how to replace a String using a regex pattern in Java.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
In this example, we will replace string "12345" with "number" by using replaceAll() method.
Original String: Hello, world! 12345 world. Modified String: Hello, world! number world.
replaceAll() and a regex pattern. \\d+) and a replacement string ("number"). replaceAll() to replace all occurrences of digits in the input string with the replacement string. In this example we will see how we can replace all "apple" with "orange" by using matcher methods.
Original String: apple, banana, apple Modified String: orange, banana, orange
Matcher and a regex pattern. Pattern.compile() method to create a pattern and Matcher to find and replace occurrences iteratively. The modified string is then printed.