确定 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