Introduce Java Regular Expressions and give examples
Java Regular Expressions (regex) are a powerful tool for pattern matching and text manipulation. They allow you to define search patterns for strings, enabling you to perform operations such as searching, replacing, and splitting strings based on specific criteria.
In Java, the java.util.regex
package provides the classes necessary for working with regular expressions. The main classes in this package are:
A regular expression is a sequence of characters that defines a search pattern. Here are some common elements of regex syntax:
a
matches the character 'a')..
, *
, +
, ?
, ^
, $
, []
, ()
, {}
, |
).[]
(e.g., [abc]
matches 'a', 'b', or 'c').*
for zero or more, +
for one or more, ?
for zero or one).^
asserts the start of a line, and $
asserts the end of a line.Here are some examples of using Java Regular Expressions:
Matching a Simple Pattern:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String text = "Hello, World!";
String pattern = "Hello";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(text);
if (matcher.find()) {
System.out.println("Pattern found!");
} else {
System.out.println("Pattern not found.");
}
}
}
Using Character Classes:
public class CharacterClassExample {
public static void main(String[] args) {
String text = "abc123";
String pattern = "[a-z]"; // Matches any lowercase letter
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(text);
while (matcher.find()) {
System.out.println("Found: " + matcher.group());
}
}
}
Using Quantifiers:
public class QuantifierExample {
public static void main(String[] args) {
String text = "aaabbbccc";
String pattern = "a{2,3}"; // Matches 'aa' or 'aaa'
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(text);
while (matcher.find()) {
System.out.println("Found: " + matcher.group());
}
}
}
Replacing Text:
public class ReplaceExample {
public static void main(String[] args) {
String text = "The quick brown fox jumps over the lazy dog.";
String pattern = "fox";
String replacement = "cat";
String result = text.replaceAll(pattern, replacement);
System.out.println(result); // Output: The quick brown cat jumps over the lazy dog.
}
}
Splitting a String:
public class SplitExample {
public static void main(String[] args) {
String text = "one,two;three four|five";
String pattern = "[,; |]+"; // Split on comma, semicolon, space, or pipe
String[] result = text.split(pattern);
for (String s : result) {
System.out.println(s);
}
}
}
Java Regular Expressions provide a flexible and powerful way to work with text. By understanding the syntax and using the Pattern
and Matcher
classes, you can perform complex string manipulations efficiently. Regular expressions can be particularly useful for tasks such as input validation, data parsing, and text processing.