-2

is there any efficient standard java library except String's split method that can help in counting the occurance of a given regex pattern in a given String object

Guys please throw some comments on below approach:

String s = "AA---AA---AA";
String[] temp = s.split("AA");
int count = temp.length - 1;
JBourne
  • 335
  • 1
  • 3
  • 12

2 Answers2

1

The efficient way is to use a loop. The standard library doesn't provide a method to do this.

Something like this:

Matcher m = Pattern.compile(regex).matcher(input);
int count = 0;
while (m.find()) {
    count++;
}

The approach of using String.split(separator) is probably1 less efficient, because it entails creating an array containing the string segments. There is certainly no sound reason to think that the computational complexity of split is different to the approach with the loop.


1 - I haven't bothered to measure this. If this is something that matters to you, you should construct a benchmark ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • have added another approach in question details, which one appears to have lower time complexity ?? – JBourne Jun 29 '14 at 15:21
0
import java.util.regex.*;

class RegexCount {
    public static void main(String[] args) {
        String test = "Test---Test---Test";
        Pattern pattern = Pattern.compile("Test");
        Matcher  matcher = pattern.matcher(test);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);
    }
}

Output: 3

David Pullar
  • 706
  • 6
  • 18