The mistake of calling matcher.goup() without a prior call to matcher.find(), matcher.matches(), or matcher.lookingAt()

This annoying mistake is found in many programs. As the heading says, these are cases where programmers call any of the group() methods without a prior call to the find, matches, or lookingAt methods. A matcher is created using the pattern.matcher(String) method call, but we need to invoke one of these three methods to perform a match operation.

If we call matcher.group() without calling one of these three methods, then the code will throw a java.lang.IllegalStateException exception, as the following code is doing:

package example.regex; 
  
import java.util.regex.*;  
  
public class MissingMethodCall  
{  
  public static void main(String[] args)  
  {  
    final Pattern p = Pattern.compile("(\d*)\.?(\d+)");  
    final String input = "123.75";  
  
    Matcher m = p.matcher(input);  
    System.out.printf("Number Value [%s], Decimal Value [%s]%n", 
    m.group(1), m.group(2));  
  }  
} 

Note that the code calls m.group(1) and m.group(2) right after it instantiates the matcher object from a pattern instance. Once compiled and executed, this code will throw an unwanted java.lang.IllegalStateException exception, indicating that the matcher instance is not in the correct state to return group information.

In order to fix this code, insert a call to any one of the three methods (find, matches, or lookingAt) to perform a match operation, as shown in the following code:

package example.regex; 
 
import java.util.regex.*; 
 
public class RightMethodCall 
{ 
  public static void main(String[] args) 
  { 
    final Pattern p = Pattern.compile("(\d*)\.?(\d+)"); 
    final String input = "123.75"; 
 
    Matcher m = p.matcher(input); 
     
    if (m.find()) // or m.lookingAt() or m.matches() 
    { 
      System.out.printf("Integer Part [%s], Fractional Part [%s]%n", 
      m.group(1), m.group(2)); 
    } 
  } 
} 

Now, this code will produce the correct output, as follows:

Integer Part [123], Fractional Part [75] 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.144.56