Java Pattern 除了compile(), 还有一个重载方法:
public static Pattern compile(String regex, int flags)
flag 就是 Pattern 类中的常量:
flag | 功能 |
---|---|
CASE_INSENSITIVE(?i) | 表示正则匹配的时候忽略大小写,US-ASCII 字符下进行。可以结合 UNICODE_CASE 的标记,基于 Unicode 的大小写不敏感的匹配就可以开启了 |
COMMENTS(?x) | 空白和 #开始直到行末的注释会被忽略掉 |
DOTALL(?s) | 这种模式下. 可以匹配所有字符,包括换行符,默认 . 匹配除换行符以外的任意字符 |
MULTILINE(?m) | 更改 ^ 和 $ 的含义,以使它们分别与任何行的开头和结尾匹配,而不只是与整个字符串的开头和结尾匹配。 注意:(?m)只有在正则表达式中涉及到多行的^ 和$ 的匹配时,才使用 Multiline 模式。 |
UNIX_LINES(?d) | 在 . 、^ 、& 的行为中只识别换行符 \n |
还有其它的 flag 标记,可自行参考 Pattern 里面的常量及解释:
来几个栗子吧:
多行模式 (?m)
多行模式下,对每一行(这行的第一个字符至每一行的结束处)都进行匹配。
public class MultiLinesFlags {
static public final String POEM =
"Twas brillig, and the slithy toves\n" +
"Did gyre and gimble in the wabe.\n" +
"All mimsy were the borogoves,\n" +
"And the mome raths outgrabe.\n\n" +
"Beware the Jabberwock, my son,\n" +
"The jaws that bite, the claws that catch.\n" +
"Beware the Jubjub bird, and shun\n" +
"The frumious Bandersnatch.";
public static void main(String[] args) {
// 这个正则表达式中有一个「$」行尾的匹配
// \S: 匹配任意不是空白符的字符
// \s: 匹配任意的空白符
Matcher m =
Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$")
.matcher(POEM);
while (m.find()) {
for (int j = 0; j <= m.groupCount(); j++)
print("[" + m.group(j) + "]");
print();
}
}
}
忽略大小写 (?i)
public class CaseSensitive {
public static void main(String[] args) {
// (?i) 忽略大小写
String reg = "(?i)((^[aeiou])|(\\s+[aeiou]))\\w+?[aeiou]\\b";
print("Regular expression: \"" + reg + "\"");
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher("Arline ate eight apples and one orange while Anita hadn't any");
while (m.find()) {
print("Match \"" + m.group() + "\" at position " +
m.start() + ((m.end() - m.start() < 2) ? "" : ("-" + (m.end() - 1))));
}
}
}
组合使用多个 flag
public class ConjunctionFlags {
public static void main(String[] args) {
Pattern p = Pattern.compile("^java",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher m = p.matcher(
"java has regex\nJava has regex\n" +
"JAVA has pretty good regular expressions\n" +
"Regular expressions are in Java");
while (m.find())
System.out.println(m.group());
}
}
PS: 上面的栗子都来自 《Java 编程思想》