기타
re.search 위치 여러개 찾기
블로그별명
2023. 2. 23. 14:52
TL;DR
import re
[(m.start(0), m.end(0)) for m in re.finditer('match', text)]
세부내용
re.search를 이용해 내가 찾고자 하는 단어의 위치를 알수있다 하지만 하나밖에 찾지못한다
s = 'cat cat cat cant cat'
m = re.search('cat', s)
print(m.span())
>>> (0, 3)
re.finditer은 정규식과 매칭되는 모든 문자열을 반복가능한 객체로 return한다
for i in re.finditer('python', '3python3, python'):
print(i)
>>> <re.Match object; span=(1, 7), match='python'>
<re.Match object; span=(10, 16), match='python'>
출처
https://stackoverflow.com/questions/3519565/find-the-indexes-of-all-regex-matches