向正则表达式添加注释
//来 自 时代Java公众号 - N o w J a v a . c o m 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); /* NowJava.com 提 供 */ // 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); // 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(