0

I'm trying to find every occurrence of ".-." in this String "-.-.-.-", so I would expect an output of 2, instead I just get 1.

If i search on this String "-.-.--.--.-.--", I expect 2 and I do get 2. So it appears to me that the search doesn't recognize individual ".-." when they're grouped next to each other. How do I fix that?

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test {
    public static void find() {
        int count = 0;
        Pattern p = Pattern.compile("\\.-\\.");
        Matcher m = p.matcher("-.-.-.-");
        while (m.find()) {
            count++;    
        }
        System.out.println(count);
    }

    public static void main(String[] args) {
        find();
    }

}
  • [How to find overlapping matches with a regexp?](https://stackoverflow.com/q/11430863) Try [like this](https://regex101.com/r/hKES9Y/1) – bobble bubble Sep 28 '19 at 08:28
  • They're not grouped next to each other, they are overlapping in your first string. You can workaround it by using a lookahead: `\.-(?=\.)` – Nick Sep 28 '19 at 08:30

2 Answers2

0

The work around for the above logic is

String p = ".-.";
String s = "-.-.-.-";
int count = 0;
for (int index = s.indexOf(pa);
    index >= 0;
    index = s.indexOf(pa, index + 1)){
         count++;
}
Rutvik Joshi
  • 97
  • 3
  • 13
0

Fixed with the lookahead as proposed by Nick and bobble bubble

Pattern p = Pattern.compile("\\.-(?=\\.)");