Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to check whether a String contains a certain substring n times. I know I can do:

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

Or even Assertions.assertThat(myString).containsOnlyOnce("xyz");

But how can I ensure this for n times?

I tried something like:

Assertions.assertThat(myString).areExactly(n, myString.contains("xyz")); but sadly this is not compilable.

Any ideas?


2 Answers

You are probably looking for StringUtils.countMatches

Counts the number of occurrences of one String in another

like image 61
Rahul Tripathi Avatar answered Dec 06 '25 15:12

Rahul Tripathi


You can have the regex like this which test String "myString" has SubString "xyz" n times.

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

You can replace n with the count of substring you want to test.

like image 22
Himank Batra Avatar answered Dec 06 '25 16:12

Himank Batra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!