Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

How to find the exact word using a regex in Java?

Consider the following code snippet:

String input = "Print this";
System.out.println(input.matches("\bthis\b"));

Output

false

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

.*\bthis\b

And if you want to allow extra text at the end of the line too:

.*\bthis\b.*

Alternatively, use a Matcher object and use Matcher.find() to find matches within the input string:

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

Output:

this

If you want to find multiple matches in a line, you can call find() and group() repeatedly to extract them all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...