程序查找字符串是否为字母数字。
包含数字和字母的任何单词都称为字母数字。以下正则表达式匹配数字和字母的组合。
"^[a-zA-Z0-9]+$";
String类的matchs方法接受正则表达式(以String的形式),并将其与当前字符串匹配,以防万一,如果match方法返回true,则返回false。
因此,要查找特定字符串是否包含字母数字值-
获取字符串。
绕过上面提到的正则表达式调用match方法。
检索结果。
例子1
import java.util.Scanner;
public class AlphanumericString {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.next();
String regex = "^[a-zA-Z0-9]+$";
boolean result = input.matches(regex);
if(result) {
System.out.println("Given string is alpha numeric");
} else {
System.out.println("Given string is not alpha numeric");
}
}
}输出结果
Enter input string: abc123* Given string is not alpha numeric
例子2
您还可以使用java.util.regex包的类和方法(API)编译正则表达式并将其与特定字符串匹配。以下程序是使用这些API编写的,它验证给定的字符串是否为字母数字。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "^[a-zA-Z0-9]+$";
String data[] = input.split(" ");
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
for (String ele : data){
//创建一个匹配对象
Matcher matcher = pattern.matcher(ele);
if(matcher.matches()) {
System.out.println("The word "+ele+": is alpha numeric");
} else {
System.out.println("The word "+ele+": is not alpha numeric");
}
}
}
}输出结果
Enter input string: hello* this$ is sample text The word hello*: is not alpha numeric The word this$: is not alpha numeric The word is: is alpha numeric The word sample: is alpha numeric The word text: is alpha numeric