java.time.MatchResult.start(int group)
方法返回在此匹配期间由给定组捕获的子序列的起始索引。
声明
以下是java.time.MatchResult.start(int group)
方法的声明。
int start(int group)
参数
group
- 此匹配器模式中捕获组的索引。
返回值
组捕获的第一个字符的索引,如果匹配成功但组本身不匹配,则返回-1
。
异常
IllegalStateException
- 如果尚未尝试匹配,或者上一个匹配操作失败。IndexOutOfBoundsException
- 如果模式中没有具有给定索引的捕获组。
示例
以下示例显示了java.time.MatchResult.start(int group)
方法的用法。
package com.yiibai;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchResultDemo {
private static final String REGEX = "(.*)(\\d+)(.*)";
private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";
public static void main(String[] args) {
// create a pattern
Pattern pattern = Pattern.compile(REGEX);
// get a matcher object
Matcher matcher = pattern.matcher(INPUT);
if(matcher.find()) {
//get the MatchResult Object
MatchResult result = matcher.toMatchResult();
//Prints the start index of the subsequence captured by the given group during this match.
System.out.println("Second Capturing Group - Match String start(1): "+result.start(1));
}
}
}
编译并运行上面的程序,这将产生以下结果 -
Second Capturing Group - Match String start(1): 0