The subexpression/metacharacter “\A” matches the beginning of the entire string.
Example 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);
}
}Output
Number of matches: 1
Example 2
Following Java program accepts a string from the user verifies whether it contains non-ASCII characters.
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