Question

Just a quick question about Java regex patterns! So say if I had a method like..

    public void example()
    {
      Pattern p = Pattern.compile("\\d*");
      Matcher m = p.matcher("ab34ef");
      boolean b = false;
      while (b = m.find()) 
      {
        System.out.println(m.start() + " " + m.group()); 
      }
    }

If I ran this I would end up with the following output..

     0
     1
     2 34
     4
     5
     6

I understand how this works apart from how it ends up at 6, I thought it would finish on 5 could someone please explain this to me? Thanks!

Was it helpful?

Solution

In your string, "ab34ef", there are 7 "empty characters" with a value of "". They are located between each of the normal characters. It attempts to find a match starting on each empty character, not each normal character; i.e. the location of each | in the following: "|a|b|3|4|e|f|".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top