본문 바로가기

WEB_Programming/Pure Java

Regular Expression > Boundary Matchers


지금까지 우리는 특정 위치에서 입력된 스트링의 부분이 맞는지 아닌지에 대해서 관심을 가졌다. 그러나 우리는 매치가 어디서 이루어 지는지에 대해서는 다루지 않았다.

boundary matchers를 이용하여 더욱 정밀하게 특정 정보에 대해서 매치되는 패턴을 만들 수 있다. 예를 들어, 부분적인 단어를 찾는데 관심을 가지고 있을때, 이 매치되는 값이 처음 라인과 끝 라인에 이 값이 나타나기를 원하는 경우가 잇을 것이다. 혹은 단어의 영역에서 매치가 이루어 지는지 알고 싶을 수 있고, 또는 이전 매치의 끝에서 이루어 지는지에 대해서 원할 수 있다.

다음은 boundary matcher의 예이다.

 Boundary Matchers
 ^  The beginning of a line
 $  The end of a line
 \b  A word boundary
 \B  A non-word boundary
 \A  The beginning of the input
 \G  The end of the previous match
 \Z  The end of the input but for the final terminator, if any
 \z  The end of the input
다음 예를 보면 boundary 매처인 ^과 $를 이용하고 있음을 보여준다. 상위에서 이야기했듯이 ^매치는 라인의 시작을 나타내며, &는 끝을 의미한다.
Enter your regex: ^dog$

Enter input string to search: dog

I found the text "dog" starting at index 0 and ending at index 3.


Enter your regex: ^dog$

Enter input string to search: dog

No match found.


Enter your regex: \s*dog$

Enter input string to search: dog

I found the text " dog" starting at index 0 and ending at index 15.


Enter your regex: ^dog\w*

Enter input string to search: dogblahblah

I found the text "dogblahblah" starting at index 0 and ending at index 11.
첫번째 예제는 성공을 한다. 왜냐하면 패턴이 입력스트링 전체에 나타나기 때문이다.  두번째 문자는 실패한다. 왜냐하면 입력 문자에서 처음 몇 문자가 공백으로 시작하기 때문이다. 세번째 예제는 패턴에서 공백 문자에 대한 제한이 없이 dog로 끝이 나도록 하고 있다. 마지막 예제는 "dog"로 시작하고, 나머지는 문자가 몇개가 와도 상관없다는 의미가 된다.

만약 word boundary에서 패턴이 시작과 끝을 제한하고자 한다면 단지 \b를 앞 뒤에 붙여주면 된다. 예를 들면 \bdog\b이다. (즉 전체 단어가 같아야 한다. 두번째 예는 단어가 정확하게 매칭이 되지 않는다.)

Enter your regex: \bdog\b

Enter input string to search: The dog plays in the yard.

I found the text "dog" starting at index 4 and ending at index 7.


Enter your regex: \bdog\b

Enter input string to search: The doggie plays in the yard.

No match found.

매치되는 단어를 non-word boundary로 매치를 원한다면, \B를 이용하면 된다.
Enter your regex: \bdog\B

Enter input string to search: The dog plays in the yard.

No match found.


Enter your regex: \bdog\B

Enter input string to search: The doggie plays in the yard.

I found the text "dog" starting at index 4 and ending at index 7.

오직 이전에 매치된 내용의 끝에서 매치가 발생되기를 원하는 경우 \G를 이용하면된다.
Enter your regex: dog

Enter input string to search: dog dog

I found the text "dog" starting at index 0 and ending at index 3.

I found the text "dog" starting at index 4 and ending at index 7.


Enter your regex: \Gdog

Enter input string to search: dog dog

I found the text "dog" starting at index 0 and ending at index 3.

여기에서 두번째 예는 오직 하나의 매치만 이루어진다. 왜냐하면 두번째 발생된 "dog"는 이전 매치의 끝에서 부터 시작되지 않기 때문이다.