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

来源:互联网 发布:java报表开发工具 编辑:程序博客网 时间:2024/06/04 23:20

先看看官方给出的说明:

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 )

0 0
原创粉丝点击