In Java, regular expressions (regex) are sequences of characters that define a search pattern. They are widely used for string manipulation and text processing tasks such as searching, splitting, replacing, and validating strings. Java provides the java.util.regex
package for working with regular expressions. Here's an overview of how to use regular expressions in Java:
Pattern and Matcher: The Pattern
class represents a compiled regular expression, and the Matcher
class is used to perform matching operations on a character sequence.
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String text = "The quick brown fox jumps over the lazy dog"; String patternString = "fox"; // Compile the regular expression pattern Pattern pattern = Pattern.compile(patternString); // Create a matcher object Matcher matcher = pattern.matcher(text); // Find matches while (matcher.find()) { System.out.println("Found match '" + matcher.group() + "' at index " + matcher.start()); } } }
Matches: The matches()
method of the String
class checks whether the entire string matches the given regular expression.
public class MatchesExample { public static void main(String[] args) { String text = "Hello123"; String patternString = "[a-zA-Z]+[0-9]+"; boolean isMatch = text.matches(patternString); System.out.println("Is there a match? " + isMatch); } }
Splitting: The split()
method of the String
class uses regular expressions to split a string into an array of substrings.
public class SplitExample { public static void main(String[] args) { String text = "apple,banana,orange"; String[] fruits = text.split(","); for (String fruit : fruits) { System.out.println(fruit); } } }
Replacement: The replaceAll()
and replaceFirst()
methods of the String
class use regular expressions to replace substrings in a string.
public class ReplacementExample { public static void main(String[] args) { String text = "The cat in the hat"; String newText = text.replaceAll("cat", "dog"); System.out.println(newText); } }