Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
Java provides support for regular expressions through the java.util.regex
package, which includes the Pattern
and Matcher
classes. Regular expressions are a powerful tool for searching, matching, and manipulating text based on patterns. In this tutorial, we will cover the basics of regular expressions in Java and provide examples of how to use them.
To create a regular expression pattern, you can use the Pattern.compile()
method. This method takes a string representing the regular expression pattern and returns a Pattern
object.
Example:
import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Pattern pattern = Pattern.compile("\\d+"); } }
In this example, the pattern \\d+
matches one or more digits.
To match a pattern against a given input string, you can create a Matcher
object using the matcher()
method of the Pattern
class. This method takes the input string as an argument and returns a Matcher
object.
Example:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "123 abc 456 def"; Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(input); } }
The Matcher
class provides several methods for searching and iterating through matches in the input string:
find()
: Searches for the next occurrence of the pattern in the input string. Returns true
if a match is found, and false
otherwise.start()
: Returns the start index of the last match found.end()
: Returns the end index of the last match found.group()
: Returns the matched substring.Example:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "123 abc 456 def"; Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println("Match found at index " + matcher.start() + ": " + matcher.group()); } } }
The Matcher
class provides methods for replacing matches in the input string:
replaceAll(String replacement)
: Replaces all occurrences of the pattern in the input string with the given replacement string.replaceFirst(String replacement)
: Replaces the first occurrence of the pattern in the input string with the given replacement string.Example:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "123 abc 456 def"; Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(input); String replaced = matcher.replaceAll("***"); System.out.println("Replaced string: " + replaced); } }
The Pattern
class provides a method for splitting strings based on a regular expression pattern:
split(CharSequence input)
: Splits the input string around matches of the pattern.Example:
import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "123,abc,456,def"; Pattern pattern = Pattern.compile(","); String[] parts = pattern.split(input); for (String part : parts) { System.out.println("Part: " + part); } } }
Java Pattern
and Matcher
Classes:
Pattern
class is used to compile regular expressions, and the Matcher
class is used to match patterns against a given input string.String regex = "pattern"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(inputString);
Common Regex Patterns in Java:
String regex = "\\d{3}-\\d{2}-\\d{4}"; // Social Security Number pattern
Matching and Extracting Text in Java with Regex:
Matcher
methods like matches()
, find()
, and group()
to match and extract text.if (matcher.matches()) { String matchedText = matcher.group(); }
Quantifiers and Character Classes in Java Regex:
*
, +
, ?
, {}
) and character classes ([...]
) enhance regex flexibility.String regex = "[A-Za-z]+"; // Match one or more letters
Java Regex Metacharacters and Escape Sequences:
^
, $
, .
, and escape sequences are used for specific matching.String regex = "\\d+\\.\\d+"; // Match decimal numbers
Java Regex for Email Validation:
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
Validating Numeric Input with Regex in Java:
String numericRegex = "\\d+"; // Match one or more digits
Replacing Text with Regex in Java:
Matcher
and String
methods for text replacement.String replacedText = matcher.replaceAll("replacement");
Java Regex Groups and Capturing:
String regex = "(\\d{2})-(\\d{2})-(\\d{4})"; // Date pattern
Lookahead and Lookbehind in Java Regex:
(?=...)
) and lookbehind ((?<=...)
) allow you to assert conditions without consuming characters.String regex = "\\d+(?=%)"; // Match digits followed by %
Java Regex Boundary Matchers:
\b
, \B
) help match patterns at word boundaries.String regex = "\\bword\\b"; // Match whole word "word"
Java Regex and the String
Class:
String
class has methods like matches()
, split()
, and replaceAll()
for regex operations.boolean isMatch = inputString.matches(regex);