javaregexintegerextract

Regexp: match triplet of a number in the givin integer


So i am fairly new to Regexp... uptill now i am using Regexp + loop :

boolean match = false; int number =0;

int number =0;

String Str1 = String.valueOf(451999277);

 for (int i=0;match1 == false;i++) {
        //check the pattern through loop
            match1 = Pattern.matches(".*" + i + i + i + ".*", Str1);
            number = i;// assigning the number (i) which is the triplet(occur 3 times in a row) in the givin int

    }

My Goal is to find a number who is a tripplet in a givin integer For example:

I want to extract : "9" from 451999277; as "9" comes 3 times i.e, "999"

but i am pretty sure there must be a solution using solely Regexp....It would be great if anybody help me find that solution...... thanks in advance


Solution

  • Use a capturing group to match a digit and then refer to it later:

    (\d)\1\1
    

    will match a digit, capture it in a group (number 1 in this case since it's the first group of the regex) and then match whatever is in group 1 twice immediately afterwards.

    Pattern regex = Pattern.compile("(\\d)\\1\\1");
    Matcher regexMatcher = regex.matcher(subject);
    if (regexMatcher.find()) {
        ResultString = regexMatcher.group();
    } 
    

    will find the first match in subject (if there is one).