How to Check for Consecutive Letters in Java
As part of its standard class library, Java includes methods for determining whether a sequence of characters, or a "pattern," is matched by any portion of a given string of characters. In particular, a pattern can test whether several letters appear in sequence within the string; for example, "gon" matches "trigonometry." You can write Java code that checks for the presence of several consecutive letters within a string.
Instructions
-
-
1
Include the following lines at the beginning of your Java code:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
-
2
Create an instance of class Pattern for the letters you want to test for, as in the following sample code:
Pattern myPattern = Pattern.compile("gon");
Replace "gon" with the sequence of any number of consecutive letters you want to test for.
-
-
3
Create an instance of class Matcher, as in the following sample code:
Matcher myMatcher = myPattern.matcher("trigonometry");
Replace "trigonometry" with the string where you want to perform the search.
-
4
Test if the string contains a match for the pattern, as in the following sample code:
if (myMatcher.find()) {
System.out.println("There was a match");
} else {
System.out.println("There was no match");
}
-
1