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

时间:2022-02-22 13:37:16

默认情况下,正则表达式 ^ 和 $ 忽略行结束符,仅分别与整个输入序列的开头和结尾匹配。如果激活 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 = ; 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();
}
}
}