Determine if a string matches a pattern exactly

This is an example of how to determine if a String matches to a Pattern exactly. Using a Matcher to check if a String matches to a specified Pattern implies that you should:

  • Compile a given String regular expression to a Pattern, using compile(string regex) API method of Pattern. The given regex in the example is the character “b”.
  • Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
  • Use matches() API method of Matcher to attempt to match the entire given region against the pattern. The method returns true if, and only if, the entire region sequence matches this matcher’s pattern.
  • You can reset the matcher with a new sequence, using reset(CharSequence) API method of Matcher.
  • You can also match the input sequence, starting at the beginning of the region, against the pattern, using lookingAt() API method of Matcher.

Let’s take a look at the code snippet that follows:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] argv) throws Exception {

  // Compile regular expression

  String paStr = "b";

  Pattern p = Pattern.compile(paStr);

  // Determine if there is an exact match

  CharSequence inStr = "a b c";

  Matcher m = p.matcher(inStr);

  boolean flag = m.matches();

  // Try a different input


  flag = m.matches();

  // Determine if pattern matches beginning of input

  flag = m.lookingAt();




This was an example of how to determine if a String matches to a Pattern exactly in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button