16

Does anyone know of a regular expression for matching on a sequence of four digits? I need a match on ascending (1234), descending (4321), or the same (1111). This would be strictly ascending/descending; 1357 shouldn't match.

2
  • Regex is not the best method to solve this problem. Commented May 21, 2010 at 18:01
  • 4
    Does 1357 count as an ascending match? What about 1289? Is 0 before 1 or after 9? Commented May 21, 2010 at 18:01

3 Answers 3

38

To match a 4-digit number consisting of the same digit:

^([0-9])\1{3}$

Or if you prefer assertion capture:

^(?=([0-9]))\1{4}$

For the rest, it may be easier to not use regex.

If ascending digits sequence must be contiguous, then simply see if it's a 4-length substring of "0123456789". Reverse the string for descending.

For non-contiguous strictly ascending sequence (e.g. 1289 a match, 1337 not a match), you can use this regex:

^(?=\d{4}$)0?1?2?3?4?5?6?7?8?9?

The assertion ensures that there are 4 digits. The rest should be obvious.


Java example

Here it is in Java, matching 4 digits, either strictly repeating, strictly increasing, or strictly decreasing.

    String[] tests = {
        "123", "12345", "3333", "1357", "1537", "7531", "2371", "1337", "0001"
    };
    for (String test : tests) {
        System.out.printf("%s = %b%n", test, test.matches(
            "^(?=\\d{4}$)(?:(.)\\1*|0?1?2?3?4?5?6?7?8?9?|9?8?7?6?5?4?3?2?1?0?)$"
        ));
    }

Output:

123 = false
12345 = false
3333 = true
1357 = true
1537 = false
7531 = true
2371 = false
1337 = false
0001 = false

The regex again is:

^          : (starting from beginning)
(?=\d{4}$) : (assert there are 4 digits to end)
(?:        : (must then match any of these three in a non-capturing group)
   (.)\1*                : all same digit
|  0?1?2?3?4?5?6?7?8?9?  : strictly increasing
|  9?8?7?6?5?4?3?2?1?0?  : strictly decreasing
)$ : (to end)
Sign up to request clarification or add additional context in comments.

3 Comments

That is some nice work. Thank you for breaking down the expression with comments.
How can we use the similar logic for the Alphabets such as I want to check in a string is there strictly increasing/decreasing alphabets? For example ABCD, GHIJ, mnop, pomn etc
Your answer should work for me but don't know why it's not returning anything when applied on 111110123456333399876.
13
public static boolean isDigitAscendingSequence(String ssn) {
    return "0123456789".contains(ssn);
}

The same logic with descending sequences

1 Comment

And maybe adding the zero on the end as well as the beginning.
10

Here it is:

^(0123|1234|2345|3456|4567|5678|6789|3210|4321|5432|6543|7654|8765|9876|0000|1111|2222|3333|4444|5555|6666|7777|8888|9999)$

2 Comments

lol. I guess I was making it more complicated than I needed to.
It can be more complicated, but less verbose. See my solution below

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.