假设用户输入文本。如何检查相应的String
是否仅由字母和数字组成?
import java.util.Scanner;
public class StringValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter your password");
String name = in.nextLine();
(inert here)
最佳答案
您可以在字符串对象上调用matches
函数。类似的东西
str.matches("[a-zA-Z0-9]*")
如果字符串仅包含字母或数字,此方法将返回 true。
String.matches 教程:http://www.tutorialspoint.com/java/java_string_matches.htm
正则表达式测试器和解释:https://regex101.com/r/kM7sB7/1
关于java - 如何检查字符串是否仅由字母和数字组成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33467536/