Determining If a String Matches a Pattern Exactly - Java Regular Expressions

Java examples for Regular Expressions:Match

Description

Determining If a String Matches a Pattern Exactly

Demo Code

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

public class Main {

  public void main(String[] argv) {
    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
  }/*w  w w .  j  a v  a2  s.  c om*/
}

Related Tutorials