Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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 Matcher找到一个模式,但在'start'方法上没有可用的匹配_Java_Regex - Fatal编程技术网

Java Matcher找到一个模式,但在'start'方法上没有可用的匹配

Java Matcher找到一个模式,但在'start'方法上没有可用的匹配,java,regex,Java,Regex,我想在正则表达式之后获取文本的a子字符串,因此我用find检查它是否存在,然后我尝试获取start/end/group,但java.lang.IllegalStateException:没有抛出可用的匹配项 String text = "Hello bob, remind me to do a lot of things today"; pattern = Pattern.compile("remind.*.to."); // Looking for "remind <anyWord>

我想在正则表达式之后获取文本的a子字符串,因此我用find检查它是否存在,然后我尝试获取start/end/group,但java.lang.IllegalStateException:没有抛出可用的匹配项

String text = "Hello bob, remind me to do a lot of things today";
pattern = Pattern.compile("remind.*.to.");
// Looking for "remind <anyWord> to "
if (pattern.matcher(text).find())
{
    pattern.matcher(text).group();
}

正则表达式被找到,因此我处于条件中,但start/任何其他int方法都会引发异常。

问题在于您再次使用pattern.matchertext,这会创建另一个Matcher实例,并且当您在新实例上调用start时,它会引发异常,因为以前从未调用过find或matches或lookingAt

您可以这样使用它:

String text = "Hello bob, remind me to do a lot of things today";
final Pattern pattern = Pattern.compile("remind.*\\hto\\h");
Matcher m = pattern.matcher(text); // create it only once
// Looking for "remind <anyWord> to "
if (m.find()) {
    System.err.println( "Start: " + m.start() + ", match: " + m.group() );
}
而不是预期的:

"remind me to do " 
您必须调用pattern.matchertext一次,为此,只需创建一个匹配器,如下所示:

Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
    String result = matcher.group();
    //output: "remind me to do a lot of things tod"
}

非常感谢您的解释+正则表达式修复。在一个答案中学习很多新东西:这是一个很棒的答案,谢谢分享。对我来说真是一门新的学问
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
    String result = matcher.group();
    //output: "remind me to do a lot of things tod"
}