用regex检查intstring中包含的特定数字。

问题描述 投票:0回答:1

我有一个字符串整数 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
java regex regular-language
1个回答
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


4
投票

你可以使用以下的regex块来确保 1 是有至少一次。

(?=.*1)

现在,在你的情况下,你可以把它们全部结合起来(积极地展望未来)。

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

演示。演示


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;
}

我知道这不是你想要的正则表达式 但我认为这是最简单的答案。

© www.soinside.com 2019 - 2024. All rights reserved.