기술(Tech, IT)/파이썬(Python)
[Tech, Python] \b (정규식)
Daniel803
2024. 3. 14. 23:14
정규식의 \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']
참고
반응형