Java 정규식에서 하위 표현식이자 메타문자인 \A는 전체 문자열의 시작 부분과 일치합니다.
일반적으로 문자열 시작을 의미하는 ^와 비슷해 보이지만, \A는 MULTILINE 모드에서도 항상 입력 전체의 시작만을 가리킨다는 점이 다릅니다. 따라서 여러 줄로 구성된 입력에서도 첫 번째 줄의 시작 여부를 정확하게 판별할 수 있습니다.
예제 1: 문자열 시작 패턴 매칭
다음 예제는 \\AHi 패턴을 사용하여 입력 문자열이 "Hi"로 시작하는지 확인하고, 일치 횟수를 출력합니다.
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 객체 생성
Pattern p = Pattern.compile(regex);
// Matcher 객체 생성
Matcher m = p.matcher(input);
int count = 0;
while (m.find()) {
count++;
}
System.out.println("Number of matches: " + count);
}
}실행 결과
Number of matches: 1
입력 문자열이 "Hi"로 시작하므로 매칭 횟수가 1로 출력됩니다. 만약 "Hi"가 문자열 중간에 있다면 \\A 조건 때문에 매칭되지 않습니다.
예제 2: ASCII 문자 검증 프로그램
다음 Java 프로그램은 사용자로부터 문자열을 입력받아 해당 문자열에 ASCII가 아닌(non-ASCII) 문자가 포함되어 있는지 검증합니다. \\A(입력 시작)와 \\z(입력 끝)를 함께 사용하여 문자열 전체 범위를 검사합니다.
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");
}
}
}실행 결과 1 — ASCII 문자만 포함된 경우
Enter the input string: What is your name Given input contains only ASCII characters
실행 결과 2 — non-ASCII 문자가 포함된 경우
Enter the input string: whÿ do we fall Given input contains non-ASCII characters
정리
- \\A: 입력(문자열)의 시작 위치와 일치
- \\z: 입력(문자열)의 끝 위치와 일치
- ^와의 차이:
^는 MULTILINE 모드에서 각 줄의 시작과 일치하지만,\\A는 어떤 플래그 설정과 무관하게 항상 전체 입력의 시작만 일치
이처럼 \\A와 \\z를 조합하면 입력 문자열 전체가 특정 패턴(예: ASCII 문자만 허용)을 만족하는지 손쉽게 검증할 수 있어, 입력값 유효성 검사에 유용하게 활용됩니다.