Java Pattern Mattcher

Posted on 2007-10-11
Last Modified: 2008-01-09
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() +;


the output is : 012333566689
however I cant understand how I got 9 whilst the highest index is 8 in my string, any clarification ?
Question by:TheSilverBullet
    LVL 86

    Accepted Solution

    >>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");
    LVL 13

    Expert Comment


    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+"
    LVL 92

    Expert Comment

    because it is matching the empty string at the *end of the line*
    LVL 86

    Expert Comment


    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    tenRun challenge 28 67
    Problem to setup 18 67
    Spring Controller - inheritance in request parameter 3 30
    strDist challenge 35 70
    If you have upgraded to Java2 update 10 on a Microsoft Windows client, you may have discovered that your Java application does not work as it did before.  For example, the colors of your Java2D graphic may be all wrong for no apparent reason. Aft…
    For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
    Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
    This video teaches viewers about errors in exception handling.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now