繁体   English   中英

使用正则表达式查找带有 @ 的单词

[英]Using regular expressions to find words with @

我正在尝试使用正则表达式查找单词,但我不知道如何使用它。

我将收到一个文本和一个单词,我必须在有和没有@#的文本中找到它,如果找到则返回true ,如果找不到则返回false

但它不能是这样的另一个词:“thisword”。

它可以是单独的,并以# 或@ 开头。

我怎么能在 Java 中做到这一点?

例子:

“@horse 是白色的”

“#horse 是白色的”

“马是白的”

“一匹马是白的”

我必须在这三个短语中找到单词 horse、#horse 和 @horse。

我想这就是你想要的:

text.matches("\\b[#@]?" + Pattern.quote(word) + "\\b");

好的...

1)是的,有办法。 这里和这里

2)我相信这会对你有所帮助

public class TestRegex {

public static void main(String[] args) {
    String word = "cat";
    Pattern p = Pattern.compile("\\b[#@]?" + Pattern.quote(word) + "\\b");

    Matcher m = p.matcher("find c@t me @cat #cat c#t cat thiscat");

    while (m.find()) {
        System.out.println(m.group(0));
    }
}

}

由于缺乏示例,您的问题尚不清楚,但是我相信这就是您的意思:

str.matches(".*(#|@)");

这匹配包含# 或@ 的字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM