Java 如何使用正则表达式验证EditText?

Java 如何使用正则表达式验证EditText?,java,android,Java,Android,我想根据以下要求验证用户名: 只接受字符或数字 至少一个字符 我试过了 public boolean validateFormat(String input){ return Pattern.compile("^[A-Za-z0-9]+$").matcher(input).matches(); } 如何执行此操作?尝试使用此正则表达式: /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/ ^(\w|\d)+$ ^指示字符串的开头 $表示

我想根据以下要求验证用户名:

只接受字符或数字 至少一个字符 我试过了

 public boolean validateFormat(String input){

        return Pattern.compile("^[A-Za-z0-9]+$").matcher(input).matches();   
 }
如何执行此操作?

尝试使用此正则表达式:

/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/
^(\w|\d)+$
^指示字符串的开头

$表示字符串的结尾

\w表示任何单词字符

\d表示任何数字

|是逻辑OR运算符

无论如何,我建议你使用一个在线正则表达式测试工具,比如。快速测试正则表达式是非常有帮助的

希望能有帮助

==更新==

在Java代码中:

final String regex = "^(\\w|\\d)+$";
final String string = "myCoolUsername12";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

if(matcher.matches()) {
   // if you are interested only in matching the full regex
}

// Otherwise, you can iterate over the matched groups (including the full match)
while (matcher.find()) { 
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

你为什么在其中考虑?你的代码有问题吗?我不知道我在其他网站上提到的。如果你使用下划线,输入字符串是可以接受的。通过使用^[A-Za-z0-9]+$,没有问题,并且应该能够很好地满足您的要求。在询问正则表达式问题时,提供有效和无效字符串的代表性列表作为测试数据,以帮助解释您的要求,这通常很有帮助。因此,作为您文本中的一个示例,我想说1234用户名是无效的,它至少不包含一个字符,但您的正则表达式允许使用Amit的答案地址。谢谢!我使用你的代码时出错了。错误指出字符串中存在非法转义字符谢谢!代码应该是^\\w |\\d,但至少有一个字符不能达到我的要求。我键入的是正则表达式,而不是实际的java代码。很明显,您应该添加转义字符。无论如何,^\\w |\\d正则表达式是不正确的,因为您删除了表示至少一个或多个的+。包括转义字符在内的正确字符是:^\\w |\\d+$。请参阅java代码的更新答案。