본문 바로가기

WEB_Programming/Pure Java

Regular Expression > Methods of the PatternSyntaxException Class


PatternSyntaxException 는 체크되지 않는 예외로 정규식 표현에서 문법 에러에 대해서 처리를 수행한다. PatternSyntaxException 클래스는 다음과 같은 메소드를 반환한다. 이것은 무엇이 잘못 되었는지 알려주는 역할을 한다. 다음 소스 코드 RegexTestHarness2.java는 test harness를 잘못된 정규식 표현에 대해서 업데이트를 수행하도록 해준다.

import java.io.Console;

import java.util.regex.Pattern;

import java.util.regex.Matcher;

import java.util.regex.PatternSyntaxException;


public class RegexTestHarness2 {


public static void main(String[] args){

Pattern pattern = null;

Matcher matcher = null;


Console console = System.console();

if (console == null) {

System.err.println("No console.");

System.exit(1);

}

while (true) {

try{

pattern =

Pattern.compile(console.readLine("%nEnter your regex: "));


matcher =

pattern.matcher(console.readLine("Enter input string to search: "));

}

catch(PatternSyntaxException pse){

console.format("There is a problem with the regular expression!%n");

console.format("The pattern in question is: %s%n",pse.getPattern());

console.format("The description is: %s%n",pse.getDescription());

console.format("The message is: %s%n",pse.getMessage());

console.format("The index is: %s%n",pse.getIndex());

System.exit(0);

}

boolean found = false;

while (matcher.find()) {

console.format("I found the text \"%s\" starting at " +

"index %d and ending at index %d.%n",

matcher.group(), matcher.start(), matcher.end());

found = true;

}

if(!found){

console.format("No match found.%n");

}

}

}

}
이 테스트를 수행할때 다음과 같은 정규식 ?i) 표현을 넣어보자. 이것은 일반적인 시나리오에 따라서 주어진 내장 플래그 표현식에 (?i)를 넣어야 하는것이다.
Enter your regex: ?i)

There is a problem with the regular expression!

The pattern in question is: ?i)

The description is: Dangling meta character '?'

The message is: Dangling meta character '?' near index 0

?i)

^

The index is: 0
이 출력을 볼때, 우리는 문법 에러에 대해서 확인할 수 있고, 물음포 아래 그 에러표시를 보여준다. 이것은 인덱스 0번째라는것을 나타내며, 시작 괄호 부분에 대해서 조사해 보면 된다.