-1

I need to find the word "best" in a string using regex but it's throwing a "no match found" error. What am I doing wrong?

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);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
frosty
  • 2,559
  • 8
  • 37
  • 73

3 Answers3

0

As per your requirement you have to find the string "best" in "the best of", so find() method suits your requirement instead of matches(). Please find the sample code snippet below:

    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");
    }

}
  • Well, no, I need to store the pattern that I found in a variable. That's why I need matches. – frosty Jan 07 '20 at 18:54
  • 1
    `find` will do the same as `matches` it just looks for a partial match instead of having to match the whole string. You still have access to groups after find. The major difference is you can call find multiple times to find each instance that matches. – SephB Jan 07 '20 at 20:24
0

Use find() not matches!

    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!");
}
  • Well, no, I need to store the pattern that I found in a variable. That's why I need matches. – frosty Jan 07 '20 at 18:54
0

What I think you want is this.

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);
}

outputs:

found: best