You can check string is alphanumeric in Java using matches() method of Matcher class. The Matcher class is provided by java.util.regex package. Below I have shared a simple Java program in which I have taken a string and I am checking it using matches() method.
您可以使用Matcher类的matchs()方法检查Java中的字符串是否为字母数字。 Matcher类由java.util.regex包提供。 在下面,我共享了一个简单的Java程序,其中使用了一个字符串,并使用matches()方法对其进行检查。
Java程序检查字符串是否为字母数字 (Java Program to Check String is Alphanumeric or not)
java.util.regex.*;
class AlphanumericExample
{
public static void main(String...s)
{
String s1="adA12", s2="[email protected]";
System.out.println(s1.matches("[a-zA-Z0-9]+"));
System.out.println(s2.matches("[a-zA-Z0-9]+"));
}
}
Output
输出量
![How to Check String is Alphanumeric in Java](https://i-blog.csdnimg.cn/blog_migrate/2ce42a37b9a4a3e3628337b3bac4224b.png)
In above example, I have used a pattern “[a-zA-Z0-9]+” inside matches() method. It means that the string can contains characters in between a to z, A to Z and 0 to 9. Here + means string can have one or more characters. matches() method returns true if the string is alphanumeric, otherwise it returns false.
在上面的示例中,我在matches()方法中使用了模式“ [a-zA-Z0-9] +”。 这意味着字符串可以包含介于a到z,A到Z和0到9之间的字符。这里+表示字符串可以包含一个或多个字符。 如果字符串是字母数字,则matchs()方法返回true,否则返回false。
Comment below if you are getting difficulty to understand anything.
如果您难以理解任何内容,请在下面评论。
翻译自: https://www.thecrazyprogrammer.com/2015/07/how-to-check-string-is-alphanumeric-in-java.html