查找字符串是否为字母数字的程序。
任何包含数字和字母的词语都称为字母数字。以下正则表达式匹配数字和字母的组合。
"^[a-zA-Z0-9]+$";
String 类的 matches 方法接受一个正则表达式(以字符串形式),并将其与当前字符串进行匹配,如果匹配,则此方法返回 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(" ");
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
for (String ele : data){
//creating a matcher object
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP