티스토리 뷰
정규식의 \b 메타 문자는 단어 경계를 나타낸다. 이는 문자를 일치시키는 것이 아니라 문자 사이의 위치를 일치시키는 것으로, 구체적으로 단어 문자(\w) 뒤에 단어가 아닌 문자(\W)가 오는 위치 또는 그 반대의 위치에 일치시킨다. 또한 첫 번째 또는 마지막 문자가 단어 문자인 경우 만자열의 시작 또는 끝에서도 일치한다. \b를 사용하면 텍스ㅌ
- 전체 단어 일치
: 'cat'이라는 단어를 문장에서 찾는데 'cat'이 다른 단어의 일부('catalog', 'bobcat' 같은 경우)가 아닌 경우를 찾을 때
import re text = "The cat scurried away from the catalog on the bobcat." pattern = r'\bcat\b' matches = re.findall(pattern, text) print(matches) # Output: ['cat']
- \b를 단어의 시작 또는 마지막에 사용하는 경우
* 'cat'으로 시작하는 단어를 찾을 때
pattern = r'\bcat\w*' matches = re.findall(pattern, "The catalog contains various categories of items.") print(matches) # Output: ['catalog', 'categories']
* 'cat'으로 끝나는 단어를 찾을 때 pattern = r'\w*cat\b' matches = re.findall(pattern, "He adopted a bobcat and a wildcat.") print(matches) # Output: ['bobcat', 'wildcat']
- 문자열(String)의 시작 또는 마지막에 일치하는 경우
pattern = r'\bword' matches = re.findall(pattern, "word is at the start") print("Start match:", matches) # Output: ['word'] matches = re.findall(pattern, "The last word") print("No start match:", matches) # Output: [] pattern = r'word\b' matches = re.findall(pattern, "The last word") print("End match:", matches) # Output: ['word']
참고
반응형
'기술(Tech, IT) > 파이썬(Python)' 카테고리의 다른 글
[Tech, Python] main method (0) | 2024.03.15 |
---|---|
[Tech, Python] re.group() (3) | 2024.03.13 |
[Tech, Python] re.compile() (0) | 2024.03.08 |
[Tech, Python] re.escape (0) | 2024.03.02 |
[Python] raw strings (0) | 2024.01.07 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 리트코드
- 티스토리챌린지
- java
- 소켓 프로그래밍
- defaultdict
- Android
- 딕셔너리
- join
- 파이썬
- socket programming
- min heap
- 이코노미스트
- Hash Map
- 안드로이드
- The Economist Espresso
- Python
- 투 포인터
- tf-idf
- The Economist
- DICTIONARY
- ml
- 이코노미스트 에스프레소
- I2C
- Computer Graphics
- leetcode
- vertex shader
- 오블완
- 머신 러닝
- C++
- machine learning
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함
반응형