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 sam开发者_C百科e (1111). This would be strictly ascending/descending; 1357 shouldn't match.
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)
public static boolean isDigitAscendingSequence(String ssn) {
return "0123456789".contains(ssn);
}
The same logic with descending sequences
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)$
精彩评论