子表达式/元字符“ \ A ”匹配整个字符串的开头。
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 Nhooo"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches: "+count); } }
输出结果
Number of matches: 1
以下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("Given input contains only ASCII characters "); } else { System.out.println("Given input contains non-ASCII characters "); } } }
Enter the input string: What is your name Given input contains only ASCII characters
Enter the input string: whÿ do we fall Given input contains non-ASCII characters