Java 如何从字符串对象中仅获取匹配的子字符串开始、结束索引
我想使用通配符功能Java 如何从字符串对象中仅获取匹配的子字符串开始、结束索引,java,regex,Java,Regex,我想使用通配符功能 如果模式是*test*,字符串是abctestbcd我必须得到开始索引=3,结束索引=6模式可以帮助您 Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); // Check all occurrences while (matcher.find()) { System.out.print("Start index: " + matcher.start())
如果模式是*test*,字符串是abctestbcd我必须得到开始索引=3,结束索引=6
模式可以帮助您
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
// Check all occurrences
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end());
System.out.println(" Found: " + matcher.group());
}
请尝试以下代码:
String searchString = "test";
String s = "abctestbcd";
int startIndex = s.indexOf("test");
int endIndex = startIndex+searchString.length()-1;
System.out.println(startIndex);
System.out.println(endIndex);
如果可以在循环中使用多个匹配项:
String searchString = "test";
String s = "abctestbcdtest";
int startIndex = -1;
do {
startIndex = s.indexOf("test", startIndex+1);
int endIndex = startIndex+searchString.length()-1;
if (startIndex != -1){
System.out.println(startIndex);
System.out.println(endIndex);
}
} while(startIndex != -1);
使用和函数的组合。这是一个简单的API调用,您确定需要帮助吗?