在 Java 正则表达式中匹配多行
javaobject oriented programmingprogramming更新于 2025/2/13 19:24:17
要匹配/搜索具有多行 − 的输入数据
获取输入字符串。
通过将 "\r?\n" 作为参数传递给 split 方法,将其拆分为一个标记数组。
使用模式类的 compile() 方法编译所需的正则表达式。
使用 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");
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的编译模式
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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

