본문 바로가기

소프트웨어/개발관련

정규 표현식을 배워보자 #08 위치지정과 패턴

원문은 ZVON의 Regular Expressions Tutorial을 참조하면됨

 

정규식에서 사용되는 위치지정 문자들 정리

^

 입력 문자열의 시작 부분에서 그 다음 나오는 문자나 부분식과 일치하는지 검사

\A

 어떤 정규식에서는 ^의 역할을 함

$

 문자열의 끝과 일치

\Z

 어떤 정규식에서는 $의 역할을 함

\b

 단어 경계(단어와 공백 사이의 위치)와 일치

 ) 'st\b' "test" st는 찾지만, "tester"와 같이 단어안에 있는 st는 찾지 않음

 !주의! test test 에서 test 사이의 빈 공간인 space와는 다른 의미

\B

 \b와 반대(비단어 경계)로 일치. "\b"의 예제의 반대 결과가 나옴

위치 지정 문자들은 자체만으로는 의미가 없으며  ^, \b, \B의 다음이나 \b, \B, $의 앞에 나오는 문자나 부분식과 함께 동작

 

Page 22


Page 23


 Page 24

Word boundary를 이용하여 선택하려는 문자열의 범위를 지정

Source

Ere iron was found or tree was hewn,    When young was mountain under moon; Ere ring was made, or wrought was woe,    It walked the forests long ago.

\A는 문자열의 시작과 매칭되며 ^과 유사하지만,…

\A matches the beginning of string. It is similar to ^, but ^ will match after each newline, if multiline strings are considered. Similarly, \Z matches only at the end of the string or before newline at the end of it. It is similar to $, but $ will match before each newline.

Test Case

Case 1

Regular Expression:

\A…

First match:

Ere iron was found or tree was hewn, When young was mountain under moon; Ere ring was made, or wrought was woe, It walked the forests long ago.

All matches:

Ere iron was found or tree was hewn, When young was mountain under moon; Ere ring was made, or wrought was woe, It walked the forests long ago.

문자열의 시작 부분

Case 2

Regular Expression:

...\Z

First match:

Ere iron was found or tree was hewn, When young was mountain under moon; Ere ring was made, or wrought was woe, It walked the forests long ago.

All matches:

Ere iron was found or tree was hewn, When young was mountain under moon; Ere ring was made, or wrought was woe, It walked the forests long ago.

문자열의 끝부분

 

 Page 25 

패턴을 지정하여 문자열을 선택

Source

AAAX---aaax---111

(?=<패턴>) 지정된 패턴이 존재하는지 확인을 하지만, 매칭되지는 않음

(?=<pattern>) will look ahead if the pattern exists, but will not include it in the hit.

Test Case

Case 1

Regular Expression:

\w+(?=X)

First match:

AAAX---aaax---111

All matches:

AAAX---aaax---111

문자X앞에 \w+(A-Z,a-z,0-9,_1개이상)가 있는 문자열을 확인하여 문자 X를 제외하고 선택

Case 2

Regular Expression:

\w+

First match:

AAAX---aaax---111

All matches:

AAAX---aaax---111

\w+(A-Z,a-z,0-9,_ 문자가 1개이상)가 있는지 확인

Case 3

Regular Expression:

\w+(?=\w)

First match:

AAAX---aaax---111

All matches:

AAAX---aaax---111

 

 

Page 26 

패턴을 지정하여 문자열을 선택

Source

AAAX---AAA

(?!<패턴>) 지정된 패턴이 존재하는지 않는지 확인

(?!<pattern>) will look ahead if the pattern exists. If it does there will be no hit..

Test Case

Case 1

Regular Expression:

AAA(?!X)

First match:

AAAX---AAA

All matches:

AAAX---AAA

AAA뒤에 X문자가 없는

Case 2

Regular Expression:

AAA

First match:

AAAX---AAA

All matches:

AAAX---AAA

AAA가 있는지 확인