Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.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_Matcher - Fatal编程技术网

在java中使用正则表达式从字符串中获取单词

在java中使用正则表达式从字符串中获取单词,java,regex,matcher,Java,Regex,Matcher,我需要使用正则表达式在字符串中找到单词“best”,但它抛出了一个“找不到匹配项”错误。我做错了什么 Pattern pattern = Pattern.compile("(best)"); String theString = "the best of"; Matcher matcher = pattern.matcher(theString); matcher.matches(); String whatYouNeed = matcher.group(1); Log.d(String.val

我需要使用正则表达式在字符串中找到单词“best”,但它抛出了一个“找不到匹配项”错误。我做错了什么

Pattern pattern = Pattern.compile("(best)");
String theString = "the best of";
Matcher matcher = pattern.matcher(theString);
matcher.matches();
String whatYouNeed = matcher.group(1);
Log.d(String.valueOf(LOG), whatYouNeed);

根据您的要求,您必须在“最佳”中找到字符串“最佳”,因此find()方法适合您的要求,而不是匹配()。请在下面找到示例代码段:

    Pattern pattern = Pattern.compile("best");
    String theString = "the best of";
    Matcher matcher = pattern.matcher(theString);
    if(matcher.find()) {
        System.out.println("found");
    }else {
        System.out.println("not found");
    }

}
使用查找()不匹配

    public static void main(String[] args){
    Pattern pattern = Pattern.compile("(best)");
    String theString = "the best of";
    Matcher matcher = pattern.matcher(theString);
    if(matcher.find())
        System.out.println("Hi!");
}

我想你想要的是这个

String theString = "the best of";

String regex = "(best)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(theString);

while (m.find()) {
    String result = m.group(1);
    System.out.println("found: " + result);
}
产出:

found: best

不,我需要存储我在变量中找到的模式。这就是我需要匹配的原因。不,我需要存储在变量中找到的模式。这就是我需要匹配项的原因。
find
将执行与
matches
相同的操作,它只查找部分匹配项,而不必匹配整个字符串。查找后,您仍然可以访问组。主要区别在于,您可以多次调用find来查找匹配的每个实例。@VictorS不是字符串“best of”?谢谢,我添加了一个答案。