Java Reference
In-Depth Information
The easiest way to find or match characters is to use the String class itself. String
instances store Unicode character sequences and provide relatively simple operations
for finding, replacing, and tokenizing characters using regular expressions.
To determine whether a string matches a regular expression, use the matches()
method. The matches() method returns true if the entire string exactly matches
the regular expression.
The following code from the
org.java8recipes.chapter12.recipe12_5.Recipe12_5 class uses two
different expressions with two strings. The regular expression matches simply confirm
that the strings match a particular pattern as defined in the variables enRegEx and
jaRegEx .
private String enText = "The fat cat sat on the mat with
a brown rat.";
private String jaText = "Fight
!";
boolean found = false;
String enRegEx = "^The \\w+ cat.*";
String jaRegEx = ".* .*";
String jaRegExEscaped = ".*\u6587\u5B57.*";
found = enText.matches(enRegEx);
if (found) {
System.out.printf("Matches %s.\n", enRegEx);
}
found = jaText.matches(jaRegEx);
if (found) {
System.out.printf("Matches %s.\n", jaRegEx);
}
found = jaText.matches(jaRegExEscaped);
if (found) {
System.out.printf("Matches %s.\n", jaRegExEscaped);
}
This code prints the following:
Search WWH ::




Custom Search