regex

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

  m.reset("b");

  flag = m.matches();


  // Determine if pattern matches beginning of input

  flag = m.lookingAt();

    }
}

Output:

false
true
true

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

Ilias Tsagklis

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

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

0 Comments
Inline Feedbacks
View all comments
Back to top button