匹配 Java 正则表达式中的多行文本
用多行匹配/搜索输入数据 -
获取输入字符串。
通过将 "\r?\n" 作为参数传递给 split 方法,将它拆分为一组标记。
使用 pattern 类的 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");
//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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP