Java 中的正则表达式"A"构造
javaobject oriented programmingprogramming更新于 2024/5/2 19:24:17
子表达式/元字符"\A"与整个字符串的开头匹配。
示例 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\AHi";
String input = "Hi how are you welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("匹配数:"+count);
}
}
输出
匹配数:1
示例 2
以下 Java 程序接受来自用户的字符串并验证其是否包含非 ASCII 字符。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartingOfInput {
public static void main( String args[] ) {
String regex = "\A\p{ASCII}*\z";
Scanner sc = new Scanner(System.in);
System.out.println("Enter the input string: ");
String input = sc.nextLine();
//创建一个 Pattern 对象
Pattern p = Pattern.compile(regex);
//创建 Matcher 对象
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("给定的输入仅包含 ASCII 字符 ");
} else {
System.out.println("给定的输入包含非 ASCII 字符 ");
}
}
}
输出 1
输入字符串: What is your name 给定的输入仅包含 ASCII 字符
输出 2
输入字符串: whÿ do we fall 给定的输入包含非 ASCII 字符
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

