As many other commentators of this question I believe that this should not be done with regex. Regex is cool if you want to match repeating patterns of digits (like 111
), but not for arbitrary sequences of digits (like 123
or 246
). Since I was interested in the topic I wrote this code.
The input string may be any sequence of characters (digits mixed with non-digits) and all consecutive digits of the given length will be returned.
public class ConNumberParser {
public static List<String> findConsecutiveNumbers(String s, int length) {
LinkedList<String> matches = new LinkedList<>();
// seek to first digit
int i = 0;
while (i < s.length() && !Character.isDigit(s.charAt(i))) {
i++;
}
// store the beginning of a consecutive series
Integer matchedIndex = i;
// and the direction
Boolean increasing = null;
for (i++; i < s.length(); i++) {
final char c = s.charAt(i);
if (Character.isDigit(c)) {
if (null == matchedIndex) {
// first digit after other characters
matchedIndex = i;
increasing = null;
continue;
}
int difference = Character.getNumericValue(c) - Character.getNumericValue(s.charAt(i - 1));
if (Math.abs(difference) > 1) {
// no conescutive digits
matchedIndex = i;
increasing = null;
continue;
}
if (length > 2) {
if (null == increasing) {
// found first consecutive digit
increasing = (difference == 1);
continue;
}
final int expectedDiff = increasing ? 1 : -1;
if (difference != expectedDiff) {
// no conescutive digits in the right direction
matchedIndex = i - 1;
increasing = (difference == 1);
continue;
}
}
if (i - matchedIndex + 1 == length) {
// consecutive digits of given length found
matches.add(s.substring(matchedIndex, matchedIndex + length));
matchedIndex++; // move by one to keep matching overlapping
// sequences
}
} else {
matchedIndex = null;
}
}
return matches;
}
public static void main(String[] args) {
String test = "A12345b321";
List<String> m = findConsecutiveNumbers(test, 3);
System.out.print(test + " length=3: ");
System.out.println(m.toString());
String test2 = "Ax.*1290134543b3210";
List<String> m2 = findConsecutiveNumbers(test2, 3);
System.out.print(test2 + " length=3: ");
System.out.println(m2.toString());
List<String> m3 = findConsecutiveNumbers(test2, 2);
System.out.print(test2 + " length=2: ");
System.out.println(m3.toString());
}
}
Which yields the expected result:
A12345b321 length=3: [123, 234, 345, 321]
Ax.*1290134543b3210 length=3: [345, 543, 321, 210]
Ax.*1290134543b3210 length=2: [12, 01, 34, 45, 54, 43, 32, 21, 10]
9
be10
or0
, or maybe such case can't exists? – Pshemo Apr 8 '14 at 9:28