如何使用正则表达式检查字符串是否仅包含特定字符

时间:2017-02-23 09:26:54

标签: java regex string

我在Java中有一长串数字。我想找到的字符串包含任何一个数字0,1,4,6,8,9或不。 我不想检查我的字符串是否只包含任何随机数字。

我不在乎数字存在多少次。如果字符串中出现上述任何一个数字,即使只有一次,我想在那里停止并返回true。

可以使用什么正则表达式匹配此字符串?

有没有更快的方法来代替使用正则表达式? 我使用的是Java 8。

编辑:我已在网上找到很多解决方案,用于检查字符串是否包含数字。这些解决方案在这里不起作用,因为我想最佳找出我的字符串(长度约为10 ^ 15个字符)是否包含特定数字。

2 个答案:

答案 0 :(得分:2)

您可以使用模式.*[014689].*String.matches()

String input = "1 Hello World";
if (input.matches(".*[014689].*")) {
    System.out.println("Match!");
}

答案 1 :(得分:-2)

if (preg_match('/[^|]/', $string)) {    
// string contains characters other than |  
}          

或:

if (strlen(str_replace('|', '', $string)) > 0) {   
// string contains characters other than |  
}  
相关问题