Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
边界Java正则表达式不起作用_Java_Regex_Boundary - Fatal编程技术网

边界Java正则表达式不起作用

边界Java正则表达式不起作用,java,regex,boundary,Java,Regex,Boundary,你能告诉我为什么这个表达式不返回TRUE public class test { public static void main(String[] args) throws IOException{ String str = "The dog plays"; boolean t = str.matches("\\bdog\\b"); System.out.println(t); } } matches方法将始终尝试匹配整个字符串。它不是匹配特定字符串的合适

你能告诉我为什么这个表达式不返回
TRUE

public class test  {

public static void main(String[] args) throws IOException{

    String str = "The dog plays";
    boolean t = str.matches("\\bdog\\b");

    System.out.println(t);

  }
}

matches
方法将始终尝试匹配整个字符串。它不是匹配特定字符串的合适方法。所以把你的正则表达式改成

".*\\bdog\\b.*"
为了使matches方法返回true

String str = "dog plays";
System.out.println(str.matches(".*\\bdog\\b.*"));
输出:

true
true
false
\b
称为单词边界,匹配单词字符和非单词字符。请注意,上面的正则表达式也将匹配字符串
foo:dog:bar
。如果你想让狗成为一个单独的词,我建议你使用这个正则表达式

".*(?<!\\S)dog(?!\\S).*"

这将返回false,因为它试图匹配整个字符串。
有关更多详细信息,请参阅:


因此,要实现这一点,请使用Avinash正确说过的
“*\\bdog\\b.*”

对于
匹配器类:

  • matches()
    如果整个字符串与表达式匹配,则返回true

  • find()
    如果字符串的任何子序列与表达式匹配,则返回true

所以很可能这就是你想要的:

public class Test {

    public static void main(String[] args) {

        String str = "The dog plays";
        boolean t = str.find("\\bdog\\b");

        System.out.println(t);

    }
}

@拉胡尔:应该匹配。你能再检查一下吗。
public class Test {

    public static void main(String[] args) {

        String str = "The dog plays";
        boolean t = str.find("\\bdog\\b");

        System.out.println(t);

    }
}