Adding Comments to a Regular Expression - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Description

Adding Comments to a Regular Expression

Demo Code


import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  void m() throws Exception {
    CharSequence inputStr = "a b";
    String patternStr = "a b";

    // Compile without comments
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(inputStr);
    boolean matchFound = matcher.matches(); 
    System.out.println(matchFound);

    // Compile with comments
    pattern = Pattern.compile(patternStr, Pattern.COMMENTS);
    matcher = pattern.matcher(inputStr);
    matchFound = matcher.matches(); // false
    System.out.println(matchFound);

    // Use COMMENTS but include a character class with a space
    patternStr = "a  [\\ ]  b";
    pattern = Pattern.compile(patternStr, Pattern.COMMENTS);
    matcher = pattern.matcher(inputStr);
    matchFound = matcher.matches(); // true
    System.out.println(matchFound);
    //from   w w w  .j av  a  2  s.com
    // Use an inline modifier
    matchFound = pattern.matches("a b", inputStr); // true
    System.out.println(matchFound);
    matchFound = pattern.matches("(?x)a b", inputStr); // false
    System.out.println(matchFound);
    matchFound = pattern.matches("(?x)a [\\ ] b", inputStr); // true
    System.out.println(matchFound);
    matchFound = pattern.matches("(?x)a \\s b", inputStr); // true
    System.out.println(matchFound);
    matchFound = pattern.matches("a (?x:  b   )", inputStr); // true
    System.out.println(matchFound);

    // Tabs and newlines in the pattern are ignored as well
    matchFound = pattern.matches("(?x)a \t\n \\s b", inputStr); // true
    System.out.println(matchFound);
    // Read pattern from file
    try {
      File f = new File("pattern.txt");
      FileReader rd = new FileReader(f);
      char[] buf = new char[(int) f.length()];
      rd.read(buf);
      patternStr = new String(buf);

      matcher = pattern.matcher(inputStr);
      matchFound = matcher.matches(); // true
    } catch (IOException e) {
    }
  }
}
# This pattern matches ``a b''
  a     # this is the first part
  [\ ]  # this is the second part
  b     # this is the third part

Related Tutorials