Saturday, 15 February 2020

Regular Expression : matches vs find

‘matches’ method return true if the entire sequence matches to given regular expression. Whereas ‘find’ method scans the input sequence looking for the next subsequence that matches the pattern.

matches method example
import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);
                
                System.out.println("Is pattern matched : " + matcher.matches());
                System.out.println();
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output
Enter Regular Expression
a*b
Enter the string
abbb
Is pattern matched : false

Enter the string
aaab
Is pattern matched : true

Enter the string
xb
Is pattern matched : false

find method example
RegExHarness.java
import java.util.regex.*;
import java.io.*;

public class RegExHarness {
    public static void main(String args[]) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        Pattern pattern;
        Matcher matcher;
        
        String regex;
        String text;
              
        System.out.println("Enter Regular Expression");
        regex = br.readLine();
        pattern = Pattern.compile(regex);
        
        while(true){
            try{
                System.out.println("Enter the string");
                text = br.readLine();
                matcher = pattern.matcher(text);

                while(matcher.find()){
                    System.out.print("I found the text " + matcher.group());
                    System.out.print(" starting at index " + matcher.start());
                    System.out.println(" Ending at index " + matcher.end());
                }
            }
            catch(IOException e){
                System.out.println(e);
            }
        }     
    }
}

Sample Output
Enter Regular Expression
is
Enter the string
this is easy task... is it?
I found the text is starting at index 2 Ending at index 4
I found the text is starting at index 5 Ending at index 7
I found the text is starting at index 21 Ending at index 23



Previous                                                    Next                                                    Home

No comments:

Post a Comment