Skip to main content

APIzation: Replication Package

[Q#9464261][A#9464309] How to find the exact word using a regex in Java?

https://stackoverflow.com/q/9464261

Consider the following code snippet: Output What could be possibly wrong with this approach? If it is wrong, then what is the right solution to find the exact word match? PS: I have found a variety of similar questions here but none of them provide the solution I am looking for. Thanks in advance.

Answer

https://stackoverflow.com/a/9464309

When you use the matches() method, it is trying to match the entire input. In your example, the input "Print this" doesn't match the pattern because the word "Print" isn't matched. So you need to add something to the regex to match the initial part of the string, e.g. And if you want to allow extra text at the end of the line too: Alternatively, use a Matcher object and use Matcher.find() to find matches within the input string: Output: If you want to find multiple matches in a line, you can call find() and group() repeatedly to extract them all.

APIzation

.*\\bthis\\b
.*\\bthis\\b.*
Pattern p = Pattern.compile("\\bthis\\b");
    Matcher m = p.matcher("Print this");
    m.find();
    System.out.println(m.group());
this
package com.stackoverflow.api;

public class Human9464309 {

  public static boolean hasWord(String pWord, String pText) {
    Pattern p = Pattern.compile("\\b+pWord+\\b");
    Matcher m = p.matcher(pText);

    m.find();
    System.out.println(m.group());

    return m.group();
  }
}

package com.stackoverflow.api;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * How to find the exact word using a regex in Java?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/9464309">https://stackoverflow.com/a/9464309</a>
 */
public class APIzator9464309 {

  public static String findWord() throws Exception {
    Pattern p = Pattern.compile("\\bthis\\b");
    Matcher m = p.matcher("Print this");
    m.find();
    return m.group();
  }
}