기술(Tech, IT)/파이썬(Python)

[Tech, Python] \b (정규식)

Daniel803 2024. 3. 14. 23:14

정규식의 \b 메타 문자는 단어 경계를 나타낸다. 이는 문자를 일치시키는 것이 아니라 문자 사이의 위치를 일치시키는 것으로, 구체적으로 단어 문자(\w) 뒤에 단어가 아닌 문자(\W)가 오는 위치 또는 그 반대의 위치에 일치시킨다. 또한 첫 번째 또는 마지막 문자가 단어 문자인 경우 만자열의 시작 또는 끝에서도 일치한다. \b를 사용하면 텍스ㅌ

 

  1. 전체 단어 일치
    : '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']​
  2. \b를 단어의 시작 또는 마지막에 사용하는 경우

    * 'cat'으로 시작하는 단어를 찾을 때
    pattern = r'\bcat\w*'
    
    matches = re.findall(pattern, "The catalog contains various categories of items.")
    print(matches)  # Output: ['catalog', 'categories']​

    * 'cat'으로 끝나는 단어를 찾을 때

  3. pattern = r'\w*cat\b' matches = re.findall(pattern, "He adopted a bobcat and a wildcat.") print(matches) # Output: ['bobcat', 'wildcat']​
  4. 문자열(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']​

 

참고

- https://docs.python.org/ko/3/howto/regex.html

- https://velog.io/@cha-suyeon/%EC%A0%95%EA%B7%9C-%ED%91%9C%ED%98%84%EC%8B%9D-%EB%A9%94%ED%83%80-%EB%AC%B8%EC%9E%90-A-Z-b-B

'기술(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