如何在Java中使用正则表达式找到确切的单词? [英] How to find the exact word using a regex in Java?

查看:231
本文介绍了如何在Java中使用正则表达式找到确切的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

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

输出

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:我在这里找到了各种类似的问题,但没有一个能提供我想要的解决方案。
提前致谢。

PS: I have found a variety of similar questions here but none of them provide the solution I am looking for. Thanks in advance.

推荐答案

当你使用 matches()方法,它试图匹配整个输入。在您的示例中,输入打印此与模式不匹配,因为单词Print不匹配。

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.*

或者,使用 Matcher 对象并使用 Matcher.find()在输入字符串中找到匹配

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

输出:

this

如果你想在一行中找到多个匹配项,你可以致电 find() group()重复提取它们。

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

这篇关于如何在Java中使用正则表达式找到确切的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆