Java Reference
In-Depth Information
3-8. Finding Text Matches
Problem
You want to search a body of text for a particular sequence of characters.
Solution #1
Make use of regular expressions and the string matches() helper method to determ-
ine how many matches exist. To do this, simply pass a string representing a regular ex-
pression to the matches() method against any string you are trying to match. In do-
ing so, the string will be compared with the string that matches() is being called
upon. Once evaluated, matches() will yield a boolean result, indicating whether it
is a match. The following code excerpt contains a series of examples using this tech-
nique. The comments contained within the code explain each of the matching tests.
String str = "Here is a long String...let's find
a match!";
// This will result in a "true" since it is an exact match
boolean result = str.matches("Here is a long
String...let's find a match!");
System.out.println(result);
// This will result iin "false" since the entire String
does not match
result = str.matches("Here is a long String...");
System.out.println(result);
str = "true";
// This will test against both upper & lower case
"T"...this will be TRUE
result = str.matches("[Tt]rue");
System.out.println(result);
// This will test for one or the other
result = str.matches("[Tt]rue|[Ff]alse]");
Search WWH ::




Custom Search