
Java Regex in Java
Regular Expressions (RegEx) in Java are a powerful tool used for searching, matching, and manipulating strings based on patterns. Java provides the java.util.regex
package, which contains the classes Pattern
and Matcher
to work with regular expressions.
Key Classes:
Pattern: This class is used to compile a regular expression into a pattern that can be used to match against strings.
Matcher: This class is used to perform the actual matching operations like searching, replacing, and splitting strings based on the pattern.
Basic Syntax of Regular Expressions
Regular expressions consist of characters and special symbols that define the pattern you're trying to match. Here are some basic elements:
.` : Matches any character (except line terminators).
\d
: Matches any digit (0-9).\D
: Matches any non-digit character.\w
: Matches any word character (alphanumeric + underscore).\W
: Matches any non-word character.\s
: Matches any whitespace character (spaces, tabs, line breaks).\S
: Matches any non-whitespace character.^
: Matches the start of a line.$
: Matches the end of a line.[]
: Matches any character inside the brackets (e.g.,[abc]
matches 'a', 'b', or 'c').|
: Logical OR (e.g.,abc|def
matches 'abc' or 'def').()
: Groups expressions together.+
: Matches one or more occurrences of the preceding character or group.*
: Matches zero or more occurrences.?
: Matches zero or one occurrence.{n,m}
: Matches betweenn
andm
occurrences.
Common Methods in Pattern
and Matcher
Pattern.compile(String regex): Compiles the given regular expression into a pattern.
Matcher.matches(): Returns
true
if the entire string matches the regular expression.Matcher.find(): Finds the next occurrence of the regular expression in the string.
Matcher.replaceAll(String replacement): Replaces all occurrences of the regular expression in the string with the given replacement string.
Matcher.split(String input): Splits the string based on the regular expression.
Examples
1. Simple Pattern Matching
This example demonstrates how to check if a string matches a given regular expression.
import java.util.regex.*;public class RegexExample { public static void main(String[] args) { String text = "Hello123"; // Define the regular expression String regex = "\\d+"; // Matches one or more digits // Compile the regex pattern Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); // Check if the text contains digits if (matcher.find()) { System.out.println("Found digits: " + matcher.group()); } else { System.out.println("No digits found."); } }}
Explanation:
\\d+
matches one or more digits.The
matcher.find()
method checks if any part of the string contains digits.
Output:
Found digits: 123
2. Pattern Matching with Groups
This example demonstrates how to use capturing groups to extract parts of a string.
import java.util.regex.*;public class RegexGroupExample { public static void main(String[] args) { String text = "John Doe, 30"; // Define a regex pattern with groups String regex = "(\\w+)\\s(\\w+),\\s(\\d+)"; // Matches a name followed by a number // Compile the regex pattern Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); // Check if the text matches the pattern if (matcher.find()) { // Extract groups String firstName = matcher.group(1); String lastName = matcher.group(2); String age = matcher.group(3); System.out.println("First Name: " + firstName); System.out.println("Last Name: " + lastName); System.out.println("Age: " + age); } else { System.out.println("No match found."); } }}
Explanation:
(\\w+)
captures one or more word characters.(\\d+)
captures one or more digits.
Output:
First Name: JohnLast Name: DoeAge: 30
3. Replacing Text with Regular Expressions
This example shows how to replace parts of a string using a regular expression.
import java.util.regex.*;public class RegexReplaceExample { public static void main(String[] args) { String text = "The quick brown fox jumps over the lazy dog."; // Define the regex pattern to replace all vowels with "*" String regex = "[aeiouAEIOU]"; // Compile the regex pattern Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); // Replace all occurrences of vowels with '*' String replacedText = matcher.replaceAll("*"); System.out.println("Original text: " + text); System.out.println("Modified text: " + replacedText); }}
Explanation:
[aeiouAEIOU]
matches any vowel (lowercase or uppercase).matcher.replaceAll("*")
replaces all occurrences of vowels with*
.
Output:
Original text: The quick brown fox jumps over the lazy dog.Modified text: Th* q**ck br*wn f*x j*mps *v*r th* l*zy d*g.
4. Splitting Strings with a Regular Expression
This example shows how to split a string based on a regular expression.
import java.util.regex.*;public class RegexSplitExample { public static void main(String[] args) { String text = "apple,banana,orange,grape"; // Define the regex pattern to split by commas String regex = ","; // Compile the regex pattern Pattern pattern = Pattern.compile(regex); String[] fruits = pattern.split(text); // Print each fruit for (String fruit : fruits) { System.out.println(fruit); } }}
Explanation:
The regular expression
","
splits the string at each comma.
Output:
applebananaorangegrape
Important Points:
Escaping Special Characters: In regular expressions, characters like
.
,*
,+
, etc., have special meanings. If you want to match them literally, you need to escape them using a backslash (\\
).Example: To match a period (dot), use
\\.
.Regular Expression Flags: You can add flags to a regular expression to modify its behavior.
Pattern.CASE_INSENSITIVE: Makes the pattern case-insensitive.
Pattern.MULTILINE: Changes the behavior of
^
and$
to match the start and end of lines, not just the start and end of the string.
Example:
Pattern pattern = Pattern.compile("abc", Pattern.CASE_INSENSITIVE);
Summary
Regular expressions are used to search, match, replace, and manipulate strings based on patterns.
The
Pattern
class is used to define a regular expression and compile it into a pattern.The
Matcher
class is used to perform matching operations on strings.Regular expressions are a powerful and flexible tool in Java for text processing.
Let me know if you'd like more advanced examples or explanations on specific regex concepts!