如何确保一个字符串恰好有 n 次子串?

How to ensure a string has a substring exactly n times?

我想检查一个String是否包含某个子串n次。我知道我能做到:

Assertions.assertThat(myString).contains("xyz");

甚至 Assertions.assertThat(myString).containsOnlyOnce("xyz");

但是我怎么能保证这n次呢?

我试过类似的方法:

Assertions.assertThat(myString).areExactly(n, myString.contains("xyz")); 但遗憾的是,这是不可编译的。

有什么想法吗?

您可能正在寻找 StringUtils.countMatches

Counts the number of occurrences of one String in another

你可以这样做:

        String testString = "XXwwYYwwLOK";
        int count = 0;
        while (testString.contains("ww")) {
            count++;
            int index = testString.indexOf("ww");
            if(index + 1 == testString.length()){
                break;
            }
            testString = testString.substring(index + 1);
        }

我没有测试这段代码,但它应该可以工作。

AssertJ 的方法是使用 Condition,但实现它需要一些工作,所以我会按照 Rahul Tripathi 的建议使用 StringUtils.countMatches。

Hamcrest 有正则表达式的匹配器。你可以做

assertThat(actual, matchesPattern("(mystring.*?){2}))

这将测试 mystring 恰好出现了两次

http://hamcrest.org/JavaHamcrest/javadoc/2.0.0.0/org/hamcrest/text/MatchesPattern.html

是的,另一个库,但对于断言,这应该是您唯一需要的。 :-)

您可以使用这样的正则表达式,测试字符串 "myString" 有子字符串 "xyz" n 次。

Assertions.assertThat(myString).containsPattern("(xyz.*?){n}");

您可以将 n 替换为您要测试的子字符串的数量。