Java 中的正则表达式“A”构建


子表达式/元字符“\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("Number of matches: "+count);
   }
}

输出

Number of matches: 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();
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      //Creating a Matcher object
      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 ");
      }
   }
}

Output 1  

Enter the input string:
What is your name
Given input contains only ASCII characters

Output 2

Enter the input string:
whÿ do we fall
Given input contains non-ASCII characters

更新日期:19-Nov-2019

164 浏览次数

开启您的 职业生涯

完成课程以获得认证

开始学习
广告