检查一个整数/字符串是否包含特定数字,使用正则表达式。

huangapple go评论56阅读模式
英文:

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

问题

我有一个字符串/整数 X: 912035374356789
我想要检查X是否包含:1, 2, 3, 4, 5, 6, 7, 8, 9, 0
出现的顺序不重要
如何使用正则表达式进行检查。
如果有任何算法,请提到,因为我想要在最小时间复杂度内完成它。

示例
示例1:61243456092 //错误,缺少7和8
示例2:864123456789 //错误,缺少0
示例3:987601234567 //正确,全部存在

英文:

I have a string/integer X: 912035374356789

i want to check if X contains : 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

答案1

得分: 4

你可以使用以下正则表达式块来确保至少出现一次1

(?=.*1)

现在,在你的情况下,你可以将它们全部组合起来(正向预查)

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

演示:演示

英文:

You can use the following regex blocks that ensure 1 is there at least once.

(?=.*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

答案2

得分: 3

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

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

英文:

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

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
9
10

答案3

得分: 0

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

public static boolean checkString(String str) {
    for (int i = 0; i &lt; 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.

huangapple
  • 本文由 发表于 2020年5月31日 03:22:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/62107628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定