Python re : search (특정 패턴의 텍스트 찾아내기)
re.serach method는 다음과 같이 사용할 수 있습니다.
re.search(pattern, string)
pattern과 맞는 text 정보를 반환합니다.
import re
str_test = 'This is example word 12345'
obj_search_test = re.search(r'example', str_test) # 1
print(obj_search_test) # 2
print(obj_search_test.span()) # 3
print(obj_search_test.group()) # 4
-- Result
<re.Match object; span=(8, 15), match='example'>
(8, 15)
example
1. example이라는 패턴을 str_test에서 찾습니다. example은 딱히 패턴 기호 형태로 명시되지 않아서 example이라는 단어 그 자체를 str_test에서 찾는다고 보면 되겠네요.
2. 이렇게 찾아진 결과물은 단순히 그 텍스트가 아니라 search 정보가 담긴 객체의 형태로 반환됩니다.
3. search 객체의 span은 찾은 텍스트의 시작 지점과 끝지점을 (시작지점, 끝지점)의 형식으로 나타냅니다.
가장 첫 글자(여기서는 T)의 위치는 0이며 1씩 증가합니다.
4. search 객체의 group은 찾은 텍스트를 담고있습니다. 여기선 example이라는 단어를 찾았으니 example이라는 텍스트를 담고있네요.
import re
str_test = 'This is example word 12345'
obj_search_test = re.search(r'e[a-z]{5}e', str_test) # 5
print(obj_search_test.span())
print(obj_search_test.group())
-- Result
(8, 15)
example
re.search에선 re.sub과 동일하게 pattern 기호를 사용할 수 있습니다.
e[a-z]{5}e 패턴을 보면
e로 시작하고 e로 끝나며 그 사이에 알파벳 소문자 5개가 있는 패턴인것이죠.
이러한 패턴을 만족하는건 str_test에서 example이라는 단어이므로 이 단어의 search 객체가 반환됩니다.
import re
str_test = 'This is example word 12345'
obj_search_test = re.search(r'[a-z]{3}', str_test) # 6
print(obj_search_test.span())
print(obj_search_test.group())
-- Result
(1, 4)
his
마찬가지로 패턴 기호를 사용했습니다.
[a-z]{3} --> 알파벳 소문자 3개가 연달아 나오는 패턴
위 같은 패턴을 str_test에서 가장 빨리 만족시키는 부분은 This의 his이죠.
따라서 이 정보가 반홥니다.
import re
str_test = 'This is example word 12345'
obj_search_test = re.search(r'[0-9]{3}', str_test)
print(obj_search_test.span())
print(obj_search_test.group())
-- Result
(21, 24)
123
[0-9]{3} --> 0~9의 숫자 3개가 반복되는 패턴
위 패턴을 가장 빨리 만족시키는 부분은 str_test에서 12345의 123 입니다.
import re
str_test = 'This is example word 12345'
obj_search_test = re.search(r'[a-z]{2}\s[a-z]{7}', str_test)
print(obj_search_test.span())
print(obj_search_test.group())
-- Result
(5, 15)
is example
위처럼 여러 가지 pattern 기호를 사용할 수 있습니다.