The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.
It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.
Java Regex API provides 1 interface and 3 classes in java.util.regex package.
java.util.regex package
The Matcher and Pattern classes provide the facility of Java regular expression. The java.util.regex package provides following classes and interfaces for regular expressions.
MatchResult interface
Matcher class
Pattern class
PatternSyntaxException class
Matcher class
It implements the MatchResult interface. It is a regex engine which is used to perform match operations on a character sequence.
No.
Method
Description
1
boolean matches()
test whether the regular expression matches the pattern.
2
boolean find()
finds the next expression that matches the pattern.
3
boolean find(int start)
finds the next expression that matches the pattern from the given start number.
4
String group()
returns the matched subsequence.
5
int start()
returns the starting index of the matched subsequence.
6
int end()
returns the ending index of the matched subsequence.
7
int groupCount()
returns the total number of the matched subsequence.
Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.
No.
Method
Description
1
static Pattern compile(String regex)
compiles the given regex and returns the instance of the Pattern.
2
Matcher matcher(CharSequence input)
creates a matcher that matches the given input with the pattern.
Enter regex pattern: java
Enter text: this is java, do you know java
I found the text java starting at index 8 and ending at index 12
I found the text java starting at index 26 and ending at index 30