简体   繁体   English

正则表达式测试字符串是否包含数字

[英]Regex test whether string contains digits

I wanted to test if a string contains numbers (at least one number) so I tried out this: 我想测试一个字符串是否包含数字(至少一个数字),所以我尝试了这个:

public class Test {
private static final String DIGIT_PATTERN = "^(?=.*\\d)";
private static final Pattern DIGIT_PATTERN_COMPILED = Pattern.compile(DIGIT_PATTERN);

/**
 * 
 * @param args
 */
public static void main(String[] args) {
    String passwordOne = "123";
    String passwordTwo = "abc";

    Matcher matcher = null;

    matcher = DIGIT_PATTERN_COMPILED.matcher(passwordOne);

    if(!matcher.matches()) {
        System.out.println("Password " + passwordOne + " contains no number");
    } else {
        System.out.println("Password " + passwordOne + " contains number");
    }

    matcher = DIGIT_PATTERN_COMPILED.matcher(passwordTwo);

    if(!matcher.matches()) {
        System.out.println("Password " + passwordTwo + " contains no number");
    } else {
        System.out.println("Password " + passwordTwo + " contains number");
    }   
}
}

Unfortunately both if clauses print out that it contains no number. 不幸的是,如果条款打印出来,它不包含任何数字。 Am I using the regex wrong? 我使用正则表达式错了吗?

试试下面的正则表达式:

private static final String DIGIT_PATTERN = "\\d+";

Why not just use 为什么不用

private static final String DIGIT_PATTERN = "\\d";

That should match if there's any number in there. 如果那里有任何数字,那应该匹配。

The most basic pattern 最基本的模式

".*[0-9].*"

works for me with your code. 适合我的代码。

暂无
暂无

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

相关问题 java .contains()测试字符串是否包含+号 - java .contains() test whether string contains + sign 检查字符串是否仅包含数字且使用REGEX的数字是否相同? - Check if a String only contains digits and the digits are not the same using REGEX? 正则表达式检查字符串是否仅包含数字不起作用 - Regex check if a string contains only digits doesn't work 使用正则表达式检查 int/string 是否包含特定数字 - check a int/string contains specific digits in it using regex 用于检查字符串是否仅包含数字和运算符(但没有 2 个连续运算符)的正则表达式 - Regex expression to check if a string only contains digits and operators (but no 2 consecutive operators) 检查字符串是否只包含字母空格和引号(最好不包含正则表达式) - check whether a string contains only letters spaces and quotes (preferably no regex) 如何在Java中使用正则表达式检查字符串是否包含两个字母和数量可变的数字? - How to check with a regex if a String contains two letters and a variable amount of digits in Java? 检查字符串是否包含反斜杠? - Check whether the string contains backslash or not? 如何在Java中编写正则表达式以检查字符串是否包含两个字符空间和三个整数? - How to write a regex in java to check whether a string contains two chars space and three integers? RegEx用于捕获字符串中的数字 - RegEx for capturing digits from a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM