Matcher end() 方法及其在 Java 中的示例
java.util.regex.Matcher 类表示用于执行各种匹配操作的引擎。此类没有构造函数,你可以使用类 java.util.regex.Pattern 的 matches() 方法创建/获取此类的对象。
Matcher 类的 end() 方法返回当前对象表示的上次匹配后的偏移量。
子表达式 "[...]" 匹配输入字符串中花括号内的字符,在以下示例中,用此方法匹配字符 t。此处:
我们使用 compile() 方法编译了正则表达式。
获取了 Matcher 对象。
对每次匹配调用 matcher() 方法。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EndExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "[t]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count =0;
while (matcher.find()) {
int end = matcher.end();
System.out.println(end);
}
}
}输出
Enter input text: Hello how are you welcome to Tutorialspoint 27 32 43
由于字符 t 在输入字符串中出现了三次,你可以看到三个偏移量值(表示每次出现后在输入字符串中的位置)。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP