关于 Java 中 正则表达式的 MULTILINE 标志

先看看官方给出的说明:

MULTILINE
Enables multiline mode.
In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence. By default these expressions only match at the beginning and the end of the entire input sequence.

Multiline mode can also be enabled via the embedded flag expression (?m).

翻译过来大概就是说:

启用多行模式。
在多行模式中,表达式 ^ 和 $ 分别匹配一个行结束符号或者输入序列的末尾。在默认情况下,这些表达式只匹配整个输入序列的开始和结尾。

多行模式也可以通过嵌入标志 ?m 来启用。

我测试了一下,也就是说如果没有 MULTILINE 标志的话, ^$ 只能匹配输入序列的开始和结束;否则,就可以匹配输入序列内部的行结束符。测试代码如下:

package cn.chd.test.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class MultiLineTest {

    private String input = "abc\r\ndef";

    /* result:
     test1() begin
     0-3
     5-8
     test1() end
     */
    @Test
    public void test1() {
        String regex = "^\\w+$";
        Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(input);
        System.out.println("test1() begin");
        while (matcher.find()) {
            System.out.printf("%d-%d\n", matcher.start(), matcher.end());
        }
        System.out.println("test1() end");
    }

    /* result:
     test2() begin
     test2() end
     */
    @Test
    public void test2() {
        String regex = "^\\w+$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        System.out.println("test2() begin");
        while (matcher.find()) {
            System.out.printf("%d-%d\n", matcher.start(), matcher.end());
        }
        System.out.println("test2() end");
    }
}

参考:
Pattern (Java Platform SE 7 )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值