如何使用 Java RegEx 匹配输入的开头?
javaobject oriented programmingprogramming更新于 2024/5/5 10:52:17
您可以使用元字符"\A"匹配输入的开头。
示例
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\A[0-9]";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
int count = 0;
if(matcher.find()) {
System.out.println("Match found ");
} else {
System.out.println("Match not found ");
}
}
}
输出 1
输入字符串 12 sample text Match found
输出 2
输入字符串 sample text Match not found
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

