如何找到字符串中单词的完全匹配

时间:2014-11-25 15:44:23

标签: java regex

我有一个像这样的字符串

This is just a test-like thing. I want to test this

我想使用一个匹配test的正则表达式,这样它只能匹配测试而不是类似测试的东西。这将是什么样的正则表达式。我试过“\ btest \ b”,但它不起作用。

3 个答案:

答案 0 :(得分:3)

(?<=\\s|^)test(?=\\s|$)

试试这个。看看演示。

http://regex101.com/r/rA7aS3/14

\btest\b无法工作,因为-是一个单词边界。

答案 1 :(得分:2)

在这种情况下,单词边界\\b将不起作用,因为连字符-也被视为“非单词”字符。

使用此替代,使用空格:

String test = "This is just a test-like thing. I want to test this";
Pattern p = Pattern.compile("(?<=\\s|^)test(?=\\s|$)");
Matcher m = p.matcher(test);
while (m.find()) {
    System.out.println(String.format("Found %s at index %d%n", m.group(), m.start()));
}

输出(双关语无意)

Found test at index 42

答案 2 :(得分:0)

尝试以下正则表达式:

\stest(\.|\s)