用于匹配数字序列的正则表达式?

时间:2010-05-21 17:59:02

标签: regex

有没有人知道正则表达式是否匹配四位数的序列?我需要在升序(1234),降序(4321)或相同(1111)上进行匹配。这将严格上升/下降; 1357不应该匹配。

3 个答案:

答案 0 :(得分:32)

匹配由相同数字组成的4位数字:

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

或者如果您更喜欢断言捕获:

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

对于其他人来说,不使用正则表达式可能更容易。

如果升序数字序列必须是连续的,那么只需查看它是否是"0123456789"的4长子字符串。将字符串反转为降序。

对于非连续的严格升序序列(例如1289匹配,1337不匹配),您可以使用此正则表达式:

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

断言确保有4位数字。其余的应该是显而易见的。


Java示例

这里是Java,匹配4位数字,严格重复,严格增加或严格减少。

    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?)$"
        ));
    }

输出:

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

正则表达式再次出现:

^          : (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)

答案 1 :(得分:7)

public static boolean isDigitAscendingSequence(String ssn) {
    return "0123456789".contains(ssn);
}

与降序序列相同的逻辑

答案 2 :(得分:4)

这是:

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