使用正则表达式检查 int/string 中是否包含特定数字
check a int/string contains specific digits in it using regex
我有一个string/integerX: 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
我会像这样使用 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;
}
我知道这不是您想要的正则表达式,但我认为这是最简单的答案。
您可以使用以下正则表达式块来确保 1
至少出现一次。
(?=.*1)
现在,在您的情况下,您可以将所有这些组合起来(积极展望)
(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)
演示:demo
如果字符串只包含数字,那么您可以计算其中唯一数字的数量
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/integerX: 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
我会像这样使用 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;
}
我知道这不是您想要的正则表达式,但我认为这是最简单的答案。
您可以使用以下正则表达式块来确保 1
至少出现一次。
(?=.*1)
现在,在您的情况下,您可以将所有这些组合起来(积极展望)
(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9)
演示:demo
如果字符串只包含数字,那么您可以计算其中唯一数字的数量
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