Java 17 Recipes


-13. Finding Text Matches


Download 3.2 Mb.
Pdf ko'rish
bet60/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   56   57   58   59   60   61   62   63   ...   245
Bog'liq
Java 17 Recipes

3-13. Finding Text Matches
 Problem
You want to search a body of text for a particular sequence of characters.
 Solution 1
Use regular expressions and the matches() helper method to determine how many 
matches exist. To do this, simply pass a string representing a regular expression to the 
matches() method against any string you are trying to match. In doing so, the string is 
compared with one that matches() is being called upon. Once evaluated, the matches() 
method yields a Boolean result, indicating whether it is a match. The following code 
excerpt contains a series of examples using this technique. The comments contained 
within the code explain each of the matching tests.
Chapter 3 StringS


98
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]");
System.out.println(result);
// This will test to see if any numbers are present, in this case the
// person writing this String would be able to like any Java release!
str = "I love Java 8!";
result = str.matches("I love Java [0-9]!");
System.out.println(result);
// This will test TRUE as well...
str = "I love Java 7!";
result = str.matches("I love Java [0-9]!");
System.out.println(result);
// The following will test TRUE for any language that contains
// only one word for a name. This is because it tests for
// any alphanumeric combination. Notice the space character
// between the numeric sequence...
result = str.matches("I love .*[ 0-9]!");
System.out.println(result);
Chapter 3 StringS


99
// The following String also matches.
str = "I love Jython 2.5.4!";
result = str.matches("I love .*[ 0-9]!");
System.out.println(result);
Each of the results printed out in the example is true, except the second example 
because it does not match.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   56   57   58   59   60   61   62   63   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling