程序用于查找字符串是否为字母数字。
javaobject oriented programmingprogramming更新于 2024/5/11 6:36:17
任何包含数字和字母的单词都称为字母数字。以下正则表达式匹配数字和字母的组合。
"^[a-zA-Z0-9]+$";
String 类的 matches 方法接受正则表达式(以 String 的形式)并将其与当前字符串进行匹配,如果匹配,则此方法返回 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("输入输入字符串: ");
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 alphanumeric");
}
}
}
输出
输入输入字符串: abc123* Given string is not alphanumeric
示例 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("输入输入字符串: ");
String input = sc.nextLine();
String regex = "^[a-zA-Z0-9]+$";
String data[] = input.split(" ");
//创建一个 Pattern 对象
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");
}
}
}
}
输出
输入输入字符串: 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 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

