匹配Java正则表达式中的多行
要匹配/搜索多行输入数据-
获取输入字符串。
通过将“\r?\n”作为参数传递给split方法,将其拆分为令牌数组。
使用模式类的compile()方法编译所需的正则表达式。
使用matcher()方法检索matcher对象。
在for循环中,使用find()方法在数组的每个元素(新行)中查找匹配项。
使用reset()方法将匹配器的输入重置为数组的下一个元素。
示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchingText{
public static void main(String[] args) {
String input = "sample text line 1 \n line2 353 35 63 \n line 3 53 35";
String regex = "\\d";
String[] strArray = input.split("\r?\n");
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
for (int i = 0; i < strArray.length; i++) {
matcher.reset(strArray[i]);
System.out.println("Line:: "+(i+1));
while (matcher.find()) {
System.out.print(matcher.group()+" ");
}
System.out.println();
}
}
}输出结果
Line:: 1 1 Line:: 2 2 3 5 3 3 5 6 3 Line:: 3 3 5 3 3 5