Sunday 2 November 2014

Pattern.COMMENTS

Permits whitespace and comments in the pattern. In this mode, whitespace is ignored, and embedded comments starting with # are ignored until the end of a line.

With Pattern.COMMENTS you can put whitespace in your regex like below.

regex = " \\d{9} \\d ";

white spaces are ignored in above case, if you called the compile method the Pattern.COMMENTS option.

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 = "   \\d{9}  \\d   ";
        pattern = Pattern.compile(regex, Pattern.COMMENTS);   
        
        String[] input = { "1234567890", 
                           "9876543210"
                        };
        
        int i = 0;
        while(i < input.length){
            text = input[i];
                
            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());
            }
            i++;
        }     
    }
}

Output
Enter Regular Expression
I found the text 1234567890 starting at index 0 Ending at index 10
I found the text 9876543210 starting at index 0 Ending at index 10



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment