Java Regular Expressions
Regular expressions define patterns for strings.
Regular expressions can be used to search, edit, or process text.
Regular expressions are not limited to a single language, but there are subtle differences in each language.
Java provides the java.util.regex package, which contains the Pattern and Matcher classes for handling regex matching operations.
Regular expression example
A string is actually a simple regular expression; for example, Hello World the regular expression matches the "Hello World" string.
. (dot) is also a regular expression; it matches any single character such as "a" or "1".
The following table lists some regular expression examples and their descriptions:
| Regular expressions | Description |
|---|---|
|
this is text |
Matches the string "this is text" |
|
this\s+is\s+text |
Note the \s+. matches the text after the word "this", and \s+ can match multiple spaces, then matches the is string, and then \s+ matches multiple spaces and then the text string. This can match the example: this is text |
|
^\d+(.\d+)? |
^ defines what to start with \d+ matches one or more digits ? makes the option in parentheses optional . matches "." Examples that can be matched: "5", "1.5", and "2.21". |
For more regular expression content, refer to:Regular Expressions - Tutorial
java.util.regex package
The java.util.regex package is a package in the Java standard library used to support regex operations.
The java.util.regex package mainly includes the following three classes:
- Pattern class:
A Pattern object is a compiled representation of a regular expression. The Pattern class has no public constructor. To create a Pattern object, you must first call its public static compile method, which returns a Pattern object. This method accepts a regular expression as its first parameter.
- Matcher class:
A Matcher object is an engine that interprets and performs matching operations on the input string. Like the Pattern class, the Matcher class also has no public constructor. You need to call the matcher method of the Pattern object to obtain a Matcher object.
- PatternSyntaxException:
PatternSyntaxException is an unchecked exception class that indicates a syntax error in a regular expression pattern.
The following example uses the regular expression .runoob. to find whether the string contains runoob the substring:
Example
import
java
.
util
.
regex
.*;
class
RegexExample1
{
public
static
void
main
(
String
[
]
args
)
{
String
content
=
"
I am noob
"
"
from runoob.com.
"
;
String
pattern
=
"
.runoob.
"
;
boolean
isMatch
=
Pattern
.
matches
(
pattern
,
content
)
;
System
.
out
.
println
(
"
Does the string contain the 'runoob' substring?
"
isMatch
)
;
}
}
The example output is:
Does the string contain the 'runoob' substring? true
Capturing groups
A capturing group is a way to treat multiple characters as a single unit, created by grouping the characters within parentheses.
For example, the regular expression (dog) creates a single group containing "d", "o", and "g".
Capturing groups are numbered by counting their opening parentheses from left to right. For example, in the expression ((A)(B(C))), there are four such groups:
- ((A)(B(C)))
- (A)
- (B(C))
- (C)
You can call the matcher object's groupCount method to see how many groups the expression has. The groupCount method returns an int value indicating how many capturing groups the matcher object currently has.
There is also a special group (group(0)) that always represents the entire expression. This group is not included in the return value of groupCount.
Example
The following example shows how to find a numeric string from a given string:
RegexMatches.java file code:
import
java
.
util
.
regex
.
Matcher
;
import
java
.
util
.
regex
.
Pattern
;
public
class
RegexMatches
{
public
static
void
main
(
String
[
]
args
)
{
//
Search the string for the specified pattern
String
line
=
"
This order was placed for QT3000! OK?
"
;
String
pattern
=
"
(
\
D*)(
\
d+)(.*)
"
;
//
Creating a Pattern object
Pattern
r
=
Pattern
.
compile
(
pattern
)
;
//
Now create the matcher object
Matcher
m
=
r
.
matcher
(
line
)
;
if
(
m
.
find
(
)
)
{
System
.
out
.
println
(
"
Found value:
"
m
.
group
(
0
)
)
;
System
.
out
.
println
(
"
Found value:
"
m
.
group
(
1
)
)
;
System
.
out
.
println
(
"
Found value:
"
m
.
group
(
2
)
)
;
System
.
out
.
println
(
"
Found value:
"
m
.
group
(
3
)
)
;
}
else
{
System
.
out
.
println
(
"
NO MATCH
"
)
;
}
}
}
The compilation and execution results of the above example are as follows:
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
Found value: ! OK?
Regular expression syntax
In other languages, \ means:I want to insert a plain (literal) backslash in the regular expression; please give it no special meaning.
In Java, \ means:I want to insert a backslash for the regular expression, so the character after it has special meaning.
Therefore, in other languages (such as Perl), a single backslash \ is sufficient to have the escape effect, while in Java's regular expressions two backslashes are needed to be parsed as the escape effect in other languages. It can also be simply understood that in Java's regular expressions, two \ represent one \ in other languages, which is why the regex for a single digit is \d, and for a plain backslash is \.
System.out.print("\\"); // 输出为 \
System.out.print("\\\\"); // 输出为 \\
|
Character |
Description |
|---|---|
|
Marks the next character as a special character, a literal, a backreference, or an octal escape. For example, nmatches the character n.\n matches a newline. The sequence \\ Matches \ , \( Matches (. |
|
|
^ |
matches the position at the start of the input string. If the RegExp object's Multiline property is set, ^ also matches the position after "\n" or "\r". |
|
$ |
matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position before "\n" or "\r". |
|
* |
Matches the preceding character or subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}. |
|
+ |
Matches the preceding character or subexpression one or more times. For example, "zo+" matches "zo" and "zoo", but not "z". + is equivalent to {1,}. |
|
? |
Matches the preceding character or subexpression zero or one time. For example, "do(es)?" matches "do" in "do" or "does". ? is equivalent to {0,1}. |
|
{n} |
n is a non-negative integer. Matches exactly n times. For example, "o{2}" does not match "o" in "Bob", but matches the two "o"s in "food". |
|
{n,} |
n is a non-negative integer. Matches at least n times. For example, "o{2,}" does not match "o" in "Bob", but matches all o's in "foooood". "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*". |
|
{n,m} |
m and n is a non-negative integer, where n <= m. Matches at least n times, at most m times. For example, "o{1,3}" matches the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Note: You cannot insert a space between the comma and the number. |
|
? |
When this character immediately follows any other quantifier (*, +, ?, {n}, {n,}, {n,m}) the matching mode is "non-greedy". The "non-greedy" mode matches the shortest possible string found, while the default "greedy" mode matches the longest possible string found. For example, in the string "oooo", "o+?" matches only a single "o", while "o+" matches all "o"s. |
|
. |
Matches any single character except "\r\n". To match any character including "\r\n", use a pattern such as "[\s\S]". |
|
(pattern) |
Matches pattern and captures the matched subexpression. You can use the $0...$9 property to retrieve the captured match from the result "match" collection. To match the parenthesis characters ( ), use "(" or ")". |
|
(?:pattern) |
Matches pattern but does not capture the matched subexpression; that is, it is a non-capturing match that does not store the match for later use. This is useful for combining pattern parts with the "or" character (|). For example, 'industr(?:y|ies) is a more economical expression than 'industry|industries'. |
|
(?=pattern) |
Performs a positive lookahead search subexpression, which matches a string at the starting point of the string being matched pattern . It is a non-capturing match, meaning it cannot capture the match for later use. For example, 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". A lookahead does not consume characters; that is, after a match occurs, the next match search follows immediately after the previous match, rather than after the characters that make up the lookahead. |
|
(?!pattern) |
Performs a negative lookahead search subexpression, which matches a string not at the starting point of the string being matched pattern 's search string at its starting point. It is a non-capturing match, meaning it cannot capture the match for later use. For example, 'Windows (?!95|98|NT|2000)' matches "Windows" in "Windows 3.1" but not "Windows" in "Windows 2000". A lookahead does not consume characters; that is, after a match occurs, the next match search follows immediately after the previous match, rather than after the characters that make up the lookahead. |
|
x|y |
Matches x or y. For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food". |
|
[xyz] |
Character set. Matches any one of the contained characters. For example, "[abc]" matches "a" in "plain". |
|
[^xyz] |
Negated character set. Matches any character not contained. For example, "[^abc]" matches "p", "l", "i", "n" in "plain". |
|
[a-z] |
Character range. Matches any character within the specified range. For example, "[a-z]" matches any lowercase letter in the range "a" to "z". |
|
[^a-z] |
Negated range. Matches any character not in the specified range. For example, "[^a-z]" matches any character not in the range "a" to "z". |
|
\b |
Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches "er" in "never", but not "er" in "verb". |
|
\B |
Non-word boundary match. "er\B" matches "er" in "verb", but not "er" in "never". |
|
\cx |
Matches x A control character indicated by . For example, \cM matches Control-M or a carriage return.x 's value must be between A-Z or a-z. If not, c is assumed to be the "c" character itself. |
|
\d |
Digit character match. Equivalent to [0-9]. |
|
\D |
Non-digit character match. Equivalent to [^0-9]. |
|
\f |
Form feed match. Equivalent to \x0c and \cL. |
|
\n |
Line feed match. Equivalent to \x0a and \cJ. |
|
\r |
Matches a carriage return. Equivalent to \x0d and \cM. |
|
\s |
Matches any whitespace character, including space, tab, form feed, etc. Equivalent to [ \f\n\r\t\v]. |
|
\S |
Matches any non-whitespace character. Equivalent to [^ \f\n\r\t\v]. |
|
\t |
Tab match. Equivalent to \x09 and \cI. |
|
\v |
Vertical tab match. Equivalent to \x0b and \cK. |
|
\w |
Matches any word character, including underscore. Equivalent to "[A-Za-z0-9_]". |
|
\W |
Matches any non-word character. Equivalent to "[^A-Za-z0-9_]". |
|
\xn |
Matches n, where n is a hexadecimal escape code. A hexadecimal escape code must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". ASCII codes are allowed in regular expressions. |
|
num |
Matches num, where num is a positive integer. A backreference to a captured match. For example, "(.)\1" matches two consecutive identical characters. |
|
n |
Identifies an octal escape code or a backreference. If n has at least n capturing subexpressions before it, then n is a backreference. Otherwise, if n is an octal number (0-7), then n is an octal escape code. |
|
nm |
Identifies an octal escape code or a backreference. If nm has at least nm capturing subexpressions before it, then nm is a backreference. If nm has at least n captures, then n is a backreference followed by the character m. If neither of the two preceding cases exists, then nm matches the octal value nm, where n and m is an octal digit (0-7). |
|
nml |
When n is an octal number (0-3),m and l is an octal number (0-7), it matches the octal escape code nml. |
|
\un |
Matches n, where n is a Unicode character represented by four hexadecimal digits. For example, \u00A9 matches the copyright symbol (©). |
According to the Java Language Specification, backslashes in string literals in Java source code are interpreted as Unicode escapes or other character escapes. Therefore, two backslashes must be used in string literals to protect the regular expression from being interpreted by the Java bytecode compiler. For example, when interpreted as a regular expression, the string literal "\b" matches a single backspace character, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and will cause a compile-time error; to match the string (hello), the string literal "\\(hello\\)" must be used.
Methods of the Matcher class
Index methods
Index methods provide useful index values that precisely indicate where in the input string the match can be found:
| No. | Method and Description |
|---|---|
| 1 | **public int start() ** |
| Returns the start index of the previous match. | |
| 2 | public int start(int group) |
| Returns the start index of the subsequence captured by the given group during the previous match operation | |
| 3 | public int end() |
| Returns the offset after the last matched character. | |
| 4 | public int end(int group) |
| Returns the offset after the last character of the subsequence captured by the given group during the previous match operation. |
Find methods
Find methods are used to examine the input string and return a boolean indicating whether the pattern was found:
| No. | Method and Description |
|---|---|
| 1 | **public boolean lookingAt() ** |
| Attempts to match the input sequence starting from the beginning of the region against the pattern. | |
| 2 | **public boolean find() ** |
| Attempts to find the next subsequence of the input sequence that matches the pattern. | |
| 3 | public boolean find(int start**)** |
| Resets this matcher, then attempts to find the next subsequence of the input sequence that matches the pattern, starting from the specified index. | |
| 4 | **public boolean matches() ** |
| Attempts to match the entire region against the pattern. |
Replacement methods
Replacement methods are methods that replace text in the input string:
| No. | Method and Description |
|---|---|
| 1 | public Matcher appendReplacement(StringBuffer sb, String replacement) |
| Implements the non-terminal append and replace step. | |
| 2 | public StringBuffer appendTail(StringBuffer sb) |
| Implements the terminal append and replace step. | |
| 3 | **public String replaceAll(String replacement) ** |
| Replaces each subsequence of the input sequence that matches the pattern with the given replacement string. | |
| 4 | public String replaceFirst(String replacement) |
| Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string. | |
| 5 | public static String quoteReplacement(String s) |
| Returns a literal replacement string for the specified string. This method returns a string that works as if a literal string were passed to the Matcher class's appendReplacement method. |
The start and end methods
The following is an example that counts the number of times the word "cat" appears in the input string:
RegexMatches.java file code:
import
java
.
util
.
regex
.
Matcher
;
import
java
.
util
.
regex
.
Pattern
;
public
class
RegexMatches
{
private
static
final
String
REGEX
=
"
\
bcat
\
b
"
;
private
static
final
String
INPUT
=
"
cat cat cat cattie cat
"
;
public
static
void
main
(
String
[
]
args
)
{
Pattern
p
=
Pattern
.
compile
(
REGEX
)
;
Matcher
m
=
p
.
matcher
(
INPUT
)
;
//
Obtain the matcher object
int
count
=
0
;
while
(
m
.
find
(
)
)
{
count
++;
System
.
out
.
println
(
"
Match number
"
count
)
;
System
.
out
.
println
(
"
start():
"
m
.
start
(
)
)
;
System
.
out
.
println
(
"
end():
"
m
.
end
(
)
)
;
}
}
}
The compilation and execution results of the above example are as follows:
Match number 1
start(): 0
end(): 3
Match number 2
start(): 4
end(): 7
Match number 3
start(): 8
end(): 11
Match number 4
start(): 19
end(): 22
As you can see, this example uses word boundaries to ensure that the letters "c" "a" "t" are not merely a substring of a longer word. It also provides useful information about where matches occur in the input string.
The start method returns the start index of the subsequence captured by the given group during the previous match operation, and the end method returns the index of the last matched character plus 1.
The matches and lookingAt methods
Both the matches and lookingAt methods are used to attempt to match an input sequence pattern. Their difference is that matches requires the entire sequence to match, while lookingAt does not.
Although lookingAt does not require the entire string to match, it needs to match starting from the first character.
These two methods are often used at the beginning of the input string.
We use the following example to explain this functionality:
RegexMatches.java file code:
import
java
.
util
.
regex
.
Matcher
;
import
java
.
util
.
regex
.
Pattern
;
public
class
RegexMatches
{
private
static
final
String
REGEX
=
"
foo
"
;
private
static
final
String
INPUT
=
"
fooooooooooooooooo
"
;
private
static
final
String
INPUT2
=
"
ooooofoooooooooooo
"
;
private
static
Pattern
pattern
;
private
static
Matcher
matcher
;
private
static
Matcher
matcher2
;
public
static
void
main
(
String
[
]
args
)
{
pattern
=
Pattern
.
compile
(
REGEX
)
;
matcher
=
pattern
.
matcher
(
INPUT
)
;
matcher2
=
pattern
.
matcher
(
INPUT2
)
;
System
.
out
.
println
(
"
Current REGEX is:
"
REGEX
)
;
System
.
out
.
println
(
"
Current INPUT is:
"
INPUT
)
;
System
.
out
.
println
(
"
Current INPUT2 is:
"
INPUT2
)
;
System
.
out
.
println
(
"
lookingAt():
"
matcher
.
lookingAt
(
)
)
;
System
.
out
.
println
(
"
matches():
"
matcher
.
matches
(
)
)
;
System
.
out
.
println
(
"
lookingAt():
"
matcher2
.
lookingAt
(
)
)
;
}
}
The compilation and execution results of the above example are as follows:
Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
Current INPUT2 is: ooooofoooooooooooo
lookingAt(): true
matches(): false
lookingAt(): false
The replaceFirst and replaceAll methods
The replaceFirst and replaceAll methods are used to replace text matching the regular expression. The difference is that replaceFirst replaces the first match, while replaceAll replaces all matches.
The following example explains this functionality:
RegexMatches.java file code:
import
java
.
util
.
regex
.
Matcher
;
import
java
.
util
.
regex
.
Pattern
;
public
class
RegexMatches
{
private
static
String
REGEX
=
"
dog
"
;
private
static
String
INPUT
=
"
The dog says meow.
"
"
All dogs say meow.
"
;
private
static
String
REPLACE
=
"
cat
"
;
public
static
void
main
(
String
[
]
args
)
{
Pattern
p
=
Pattern
.
compile
(
REGEX
)
;
//
get a matcher object
Matcher
m
=
p
.
matcher
(
INPUT
)
;
INPUT
=
m
.
replaceAll
(
REPLACE
)
;
System
.
out
.
println
(
INPUT
)
;
}
}
The compilation and execution results of the above example are as follows:
The cat says meow. All cats say meow.
The appendReplacement and appendTail methods
The Matcher class also provides the appendReplacement and appendTail methods for text replacement:
See the following example to explain this functionality:
RegexMatches.java file code:
import
java
.
util
.
regex
.
Matcher
;
import
java
.
util
.
regex
.
Pattern
;
public
class
RegexMatches
{
private
static
String
REGEX
=
"
a*b
"
;
private
static
String
INPUT
=
"
aabfooaabfooabfoobkkk
"
;
private
static
String
REPLACE
=
"
"
;
public
static
void
main
(
String
[
]
args
)
{
Pattern
p
=
Pattern
.
compile
(
REGEX
)
;
//
Obtain the matcher object
Matcher
m
=
p
.
matcher
(
INPUT
)
;
StringBuffer
sb
=
new
StringBuffer
(
)
;
while
(
m
.
find
(
)
)
{
m
.
appendReplacement
(
sb
,
REPLACE
)
;
}
m
.
appendTail
(
sb
)
;
System
.
out
.
println
(
sb
.
toString
(
)
)
;
}
}
The compilation and execution results of the above example are as follows:
-foo-foo-foo-kkk
Methods of the PatternSyntaxException class
PatternSyntaxException is an unchecked exception class that indicates a syntax error in a regular expression pattern.
The PatternSyntaxException class provides the following methods to help us see what error occurred.
| No. | Method and Description |
|---|---|
| 1 | public String getDescription() |
| Gets the description of the error. | |
| 2 | **public int getIndex() ** |
| Gets the index of the error. | |
| 3 | **public String getPattern() ** |
| Gets the erroneous regular expression pattern. | |
| 4 | **public String getMessage() ** |
| Returns a multi-line string containing a description of the syntax error and its index, the erroneous regular expression pattern, and a visual indication of the error index in the pattern. |