The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.regex  [26 examples]

e424. 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

 Related Examples
e423. Quintessential Regular Expression Search Program
e425. Applying Regular Expressions on the Contents of a File
e426. Removing Duplicate Whitespace in a String
e427. Greedy and Nongreedy Matching in a Regular Expression
e428. Escaping Special Characters in a Pattern

See also: Flags    Groups    Lines    Paragraphs    Searching and Replacing    Tokenizing   


© 2002 Addison-Wesley.