Java 正则前面的「(?i)」、「(?m)」 是什么?

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 编程思想》

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值