確定 Java 正則表示式的匹配位置和長度
java.util.regex.Matcher 類中的 start() 方法返回匹配的起始位置(如果出現匹配)。
類似地,Matcher 類中的 end() 方法返回匹配的結束位置。
因此,start() 方法的返回值將是匹配的起始位置,而 end() 和 start() 方法的返回值之間的差異將是匹配的長度。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample {
public static void main(String[] args) {
int start = 0, len = -1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\d+";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
start = matcher.start();
len = matcher.end()-start;
}
System.out.println("Position of the match : "+start);
System.out.println("Length of the match : "+len);
}
}輸出
Enter input text: sample data with digits 12345 Position of the match : 24 Length of the match : 5
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP