简体   繁体   English

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

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

I have a string/integer X: 912035374356789我有一个字符串/整数X: 912035374356789

i want to check if X contains: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0我想检查 X 是否包含: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0

occurrence order is not matter发生顺序无关紧要

How do check it using regular expression.如何使用正则表达式检查它。 if there is any algorithm please mention, because i want to do it in minimum time complexity如果有任何算法请提及,因为我想以最小的时间复杂度来做

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

You can use the following regex blocks that ensure 1 is there at least once.您可以使用以下正则表达式块来确保1至少存在一次。

(?=.*1)

Now, in your case, you can combine all of them (positive look ahead)现在,在您的情况下,您可以将所有这些结合起来(积极展望)

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

Demo: demo演示:演示

If the string contains only digits then you can count the number of unique digits in it如果字符串只包含数字,那么您可以计算其中唯一数字的数量

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

and check if count is 10并检查计数是否为 10

Example例子

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());

yields产量

8 8
9 9
10 10

I would just use string.contains like this:我会像这样使用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;
}

I realize it's not a regular expression like you wanted, but I think it's the simplest answer.我意识到这不是您想要的正则表达式,但我认为这是最简单的答案。

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

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