An efficient approach would be to iterate over the characters of the string and test if each digit. Once you find the match, keep looking for the rest of the sequence. Sort of
int nDigits=0, i = 0;
CharacterIterator it = new StringCharacterIterator("very long string123456");
for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
i++;
nDigits = (ch.isDigit() ? nDigits++ : 0);
if (nDigits == 5) {
}
}
source
share