Regular Expression 정규표현식(2) Quantifiers
Quantifier
Quantifier는 수량을 나타내는 기호입니다.
RegEx 표현이 얼마나 반복되는지를 의미합니다. Occurance (0회, 1회, 2+회...)
한 글자 Character,
한글자를 나타내는 규칙인 Character Class,
글자모음 Capturing Groups 에 대해 모두 적용 가능합니다.
a?, a*, a+면 a{n,m} 이면 a가...
(dog)?, (dog)*, (dog)+, (dog){n,m} 이면 dog 가
? 은 안나오거나 하나 나오거나
* 는 모두다! 안나오거나, 하나/여러개 나오거나
+ 하나는 꼭 있는데 더나오는 것 같기도..
{n, m} n개부터 m개까지
Greedy | Reluctant | Possessive | Meaning |
---|---|---|---|
X? | X?? | X?+ | X , once or not at all |
X* | X*? | X*+ | X , zero or more times |
X+ | X+? | X++ | X , one or more times |
X{n} | X{n}? | X{n}+ | X , exactly n times |
X{n,} | X{n,}? | X{n,}+ | X , at least n times |
X{n,m} | X{n,m}? | X{n,m}+ | X , at least n but not more than m times |
주의. ? 와 * 는 한번도 글자가 한번도 안나타나도 매치됩니다. Zero-Length match
횟수 |
0 |
1 |
2+ | n~m |
? |
O |
O |
| |
* |
O |
O |
O | |
+ |
|
O |
O | |
{n, m} | O |
Greedy, Reluctant, Possessive Quantifier
우리가 알고 있던 Quantifier는 기본적으로 Greedy 방식이라고 하네요 ㅇㅁㅇ?
그런데 Greedy, Reluctant, Possessive 는 뭐죠?
Greedy | Reluctant | Possessive | Meaning |
---|---|---|---|
X? | X?? | X?+ | X , once or not at all |
X* | X*? | X*+ | X , zero or more times |
X+ | X+? | X++ | X , one or more times |
X{n} | X{n}? | X{n}+ | X , exactly n times |
X{n,} | X{n,}? | X{n,}+ | X , at least n times |
X{n,m} | X{n,m}? | X{n,m}+ | X , at least n but not more than m times |
"읽는 방향" 입니다.
읽는 방향에 따라 에 따라 매칭결과를 다르게 줍니다.
Greedy 는 뒤에서 앞으로 매칭
Reluctant 는 앞에서 뒤로 매칭
Possessive 는 Exact 매칭
input Source xfooxxxxxxfoo 에 대해
Greedy 는 뒤부터 오는데 xfoo를 찾아도 계속 앞으로 갑니다.
그리고 앞에 위치한 글자 전체를 Greedy 하게 매칭결과에 포함시킵니다.
매칭결과: xfooxxxxxxfoo
Reluctant 는 앞부터 읽어가고,
매칭결과를 만족하면 끊어갑니다.
매칭결과: xfoo, xxxxxxfoo
Possessive 는 exact 매칭입니다.
.*foo 로 간단하게 매칭결과가 끝나지 않으니
매칭결과: 없음
Enter your regex: .*foo // greedy quantifier Enter input string to search: xfooxxxxxxfoo I found the text "xfooxxxxxxfoo" starting at index 0 and ending at index 13. Enter your regex: .*?foo // reluctant quantifier Enter input string to search: xfooxxxxxxfoo I found the text "xfoo" starting at index 0 and ending at index 4. I found the text "xxxxxxfoo" starting at index 4 and ending at index 13. Enter your regex: .*+foo // possessive quantifier Enter input string to search: xfooxxxxxxfoo No match found.
정리
Quantifier 는 수량을 표시하고,
기본방식은 뒤에서부터 앞으로 매칭결과를 찾는다는 점만 기억합시다!
[ 정규표현식 포스트 ]
1. Character Classes
글자, 숫자, 공백 등을 표시하는 기법, [ ] 캐릭터 하나, ( ) 캐릭터 여러개
http://haloaround.tistory.com/admin/entry/post/?id=183
2. Quandifiers
캐릭터가 몇번 반복되는지, 그리고 어떻게 이런것들을 검색하는지
http://haloaround.tistory.com/admin/entry/post/?id=184
3. Capturing Groups & Boundary Match
매칭단위는 무엇이고 매칭결과를 어디에서 찾아야하는지 등의 검색 조건을 지정하는 기법
http://haloaround.tistory.com/admin/entry/post/?id=185
4. Java Pattern and Matcher Class
Input Sequence 리소스에서 Pattern 에 부합하는 것을 검색하는 기능
http://haloaround.tistory.com/admin/entry/post/?id=186