Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从字符串对象中仅获取匹配的子字符串开始、结束索引_Java_Regex - Fatal编程技术网

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调用,您确定需要帮助吗?