Java经典实例:在文本中匹配换行符

默认情况下,正则表达式 ^ 和 $ 忽略行结束符,仅分别与整个输入序列的开头和结尾匹配。如果激活 MULTILINE 模式,则 ^输入的开头行结束符之后(输入的结尾)才发生匹配。处于 MULTILINE 模式中时,$ 仅在行结束符之前输入序列的结尾处匹配。

import java.util.regex.Pattern;

/**
 * Created by Frank
 * 使用正则表达式在文本中查找换行符
 */
public class NLMatch {
    public static void main(String[] args) {
        String input = "I dream of engines\nmore engines, all day long";
        System.out.println("INPUT:" + input);
        System.out.println();
        String[] patt = {"engines.more engines", "ines\nmore", "engines$"};
        for (int i = 0; i < patt.length; i++) {
            System.out.println("PATTERN:" + patt[i]);
            boolean found;
            Pattern p1l = Pattern.compile(patt[i]);
            found = p1l.matcher(input).find();
            System.out.println("DEFAULT match " + found);
            // .代表任何符号(DOT ALL),
            Pattern pml = Pattern.compile(patt[i], Pattern.DOTALL | Pattern.MULTILINE);
            found = pml.matcher(input).find();
            System.out.println("Multiline match " + found);
            System.out.println();
        }
    }
}

 

posted @ 2016-11-10 14:42  FrankYou  阅读(5007)  评论(0编辑  收藏  举报