Regular Expression for matching a numeric sequence?

前端 未结 3 947
Happy的楠姐
Happy的楠姐 2020-12-06 02:04

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 b

3条回答
  •  醉话见心
    2020-12-06 02:33

    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)
    

提交回复
热议问题