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

13,970

Solution 1

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
}

Solution 2

Using matcher:

def match = (env.logs =~ /test/)
assert match.size() > 1
Share:
13,970
DenCowboy
Author by

DenCowboy

Updated on June 04, 2022

Comments

  • DenCowboy
    DenCowboy almost 2 years

    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?

  • sinclair
    sinclair over 6 years
    This does not work because for the testCount to increase this has to be called multiple times and the contains will always find the fist appearance of test ending in an endless loop if contains returns true.