• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 467
  • Last Modified:

Java Pattern Mattcher

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


public class TestPrim {
      public static void main(String args[]){
            

            Pattern p = Pattern.compile("\\d*");
      
    Matcher m = p.matcher("ab333e66f");
    boolean b = false;
    while(m.find()) {
      System.out.print(m.start() + m.group());
}

      }
}


the output is : 012333566689
however I cant understand how I got 9 whilst the highest index is 8 in my string, any clarification ?
0
TheSilverBullet
Asked:
TheSilverBullet
  • 2
1 Solution
 
CEHJCommented:
>>however I cant understand how I got 9 whilst the highest index is 8 in my string, any clarification ?

Because you've asked it to match a digit or no digit. Just ask it to match a digit

Pattern p = Pattern.compile("\\d");
0
 
Bart CremersJava ArchitectCommented:
Matches:

At index 0 -> empty string
At index 1 -> empty string
At index 2 -> 333
At index 5 -> empty string
At index 6 -> 66
At index 8 -> empty string
At index 9 -> empty string

If you want to match a single digit, do as CEHJ says and drop the *.
If you want to match at least one digit, use "\\d+"
0
 
objectsCommented:
because it is matching the empty string at the *end of the line*
0
 
CEHJCommented:
:-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now