Search code examples
javagroovy

Groovy: Check if text contains a string more than one time


I want to check if the word "test" appears more than 1 time in the logs. The following code just checks if the word 'test' appears more than 0 times in the string. (it just checks if the logs contain the word).

 if (env.logs.contains('test')) {
      xxx
}

What do I have to change to let this part of code check for more than one appearances of the word test?


Solution

  • The contains() method simply does this:

    public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;
    }
    

    Therefore you can do this to check if the value appears more than once:

    int index = env.logs.indexOf("test");
    if ((index > -1) && (env.logs.indexOf("test", index + 1) > -1) ) {
            // do something here
    }