Determining If a String Matches a Pattern Exactly

There are two ways to determine if a string exactly matches a regular expression. The first is to add the boundary matcher \A to the beginning and \z to the end of the pattern. The other way is to use Matcher.matches(), which does not require changes to the pattern.

If the pattern only needs to match the beginning of the string, use Matcher.lookingAt().

// Compile regular expression String patternStr = "b"; Pattern pattern = Pattern.compile(patternStr); // Determine if there is an exact match CharSequence inputStr = "a b c"; Matcher matcher = pattern.matcher(inputStr); boolean matchFound = matcher.matches(); // false // Try a different input matcher.reset("b"); matchFound = matcher.matches(); // true // Determine if pattern matches beginning of input matchFound = matcher.lookingAt(); // false

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.