Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

regex - Regular Expression for matching a numeric sequence?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...