Java 如何在另一个字符串中只找到世界的确切事例“is”,而不包括“this”中的“is”

Java 如何在另一个字符串中只找到世界的确切事例“is”,而不包括“this”中的“is”,java,regex,Java,Regex,我是Java新手,正在尝试学习正则表达式。我试图找到另一条线内的确切世界。下面是我想出的代码 int count = 0; String text = "This is the text which is to be searched " + "for occurrences of the word 'is'."; String patternString = "is"; Pattern p1 = Pattern.compile(patternString);

我是Java新手,正在尝试学习正则表达式。我试图找到另一条线内的确切世界。下面是我想出的代码

int count = 0;
String text
        = "This is the text which is to be searched "
        + "for occurrences of the word 'is'.";

String patternString = "is";
Pattern p1 = Pattern.compile(patternString);
Matcher m1 = p1.matcher(text);
while (m1.find()) {
    count++;
    System.out.printf("found %s %d: from index %d to index %d%n", 
            patternString, count, m1.start(), m1.end() );
}

然而,它不仅发现了一切,它还发现了这是其中的一部分,这不是我想要的。我怎么能只找到确切的病例呢

试试这个:字符串模式String=\\bis\\b

这可以通过使用负环视来实现:

String patternString = "(?<!\\w)is(?!\\w)";

根据您使用的字符串类型,正则表达式可能会变得相当复杂。然而,在最简单的情况下,您可以只使用is。注意周围的空间是。@khuderm我看不到周围有任何空间,你能详细说明一下吗?多谢各位
(?<!\w)is(?!\w)
found (?<!\w)is(?!\w) 1: from index 5 to index 7
found (?<!\w)is(?!\w) 2: from index 23 to index 25
found (?<!\w)is(?!\w) 3: from index 70 to index 72