如何在 java 中验证字符串只包含字母、数字、下划线和破折号

How to verify a string only contains letters, numbers, underscores, and dashes in java

我有一个项目,我必须编写代码来检查输入字符串是否以数字、字母、$ 或 _ 开头,以及输入字符串是否全部为字母、数字或 _ 字符。

正如评论中指出的那样。您应该尝试阅读有关 Regex 的内容。我想出了一个基本的正则表达式,它可能能够解决您的问题:

^(\d|[a-zA-Z$_]).([\da-zA-Z_])*
    |                |
    |                --------------> Match (*) zero or more digit, alphabet or _
    |
    -------------------------------> Match (.) one digit, alphabet, $ or _

我用下面的代码测试了一下:

public static void main(String[] args) {
    System.out.println("matches(_FooBar) : " + match("_FooBar"));
    System.out.println("matches(1FooBar) : " + match("1FooBar"));
    System.out.println("matches(12FooBar) : " + match("12FooBar"));
    System.out.println("matches(aFooBar) : " + match("aFooBar"));
    System.out.println("matches($FooBar) : " + match("$FooBar"));
    System.out.println("matches(-FooBar) : " + match("-FooBar"));
    System.out.println("matches($$$FooBar) : " + match("$$$FooBar"));
    System.out.println("matches(12FooBar) : " + match("12FooBar"));
    System.out.println("matches(12FooBar------) : " + match("12FooBar------"));
    System.out.println("matches($FooBar_) : " + match("$FooBar_"));
}

private static boolean match(String input) {
    Pattern p = Pattern.compile("^(\d|[a-zA-Z$_]).([\da-zA-Z_])*");
    return p.matcher(input).matches();
}

它产生这个输出:

matches(_FooBar) : true
matches(1FooBar) : true
matches(12FooBar12) : true
matches(aFooBar) : true
matches($FooBar) : true
matches(-FooBar) : false
matches($$$FooBar) : false
matches(12FooBar) : true
matches(12FooBar------) : false
matches($FooBar_) : true