匹配 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