繁体   English   中英

使用正则表达式检查 int/string 是否包含特定数字

[英]check a int/string contains specific digits in it using regex

我有一个字符串/整数X: 912035374356789

我想检查 X 是否包含: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0

发生顺序无关紧要

如何使用正则表达式检查它。 如果有任何算法请提及,因为我想以最小的时间复杂度来做

Example
ex1: 61243456092 //false 7 & 8 not present
ex2: 864123456789 //false 0 is not present
ex3: 987601234567 //true all present

您可以使用以下正则表达式块来确保1至少存在一次。

(?=.*1)

现在,在您的情况下,您可以将所有这些结合起来(积极展望)

(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)

演示:演示

如果字符串只包含数字,那么您可以计算其中唯一数字的数量

long count = string.chars().distinct().count();

并检查计数是否为 10

例子

String ex1 = "61243456092";
String ex2 = "864123456789";
String ex3 = "987601234567";

System.out.println(ex1.chars().distinct().count());
System.out.println(ex2.chars().distinct().count());
System.out.println(ex3.chars().distinct().count());

产量

8
9
10

我会像这样使用string.contains

public static boolean checkString(String str) {
    for (int i = 0; i < 10; i++) {
        if (!str.contains(Integer.toString(i))) {
            return false;
        }
    }

    return true;
}

我意识到这不是您想要的正则表达式,但我认为这是最简单的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM