programing

Python에서 정규 표현과 일치하는 모든 항목을 찾으려면 어떻게 해야 합니까?

goodjava 2022. 11. 20. 11:11

Python에서 정규 표현과 일치하는 모든 항목을 찾으려면 어떻게 해야 합니까?

내가 쓰고 있는 프로그램에서 나는 Python을 사용하도록 한다.re.search()텍스트 블록에서 일치하는 항목을 찾아 결과를 인쇄하는 기능입니다.그러나 프로그램은 텍스트 블록에서 첫 번째 일치를 찾으면 종료됩니다.

모든 일치 항목을 찾을 때까지 프로그램이 중지되지 않는 상태에서 이 작업을 반복하려면 어떻게 해야 합니까?이것을 하기 위한 기능이 따로 있나요?

사용하다re.findall또는re.finditer대신.

re.findall(pattern, string) 일치하는 문자열 목록을 반환합니다.

re.finditer(pattern, string) 개체 위에 반복기를 반환합니다.

예:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

언급URL : https://stackoverflow.com/questions/4697882/how-can-i-find-all-matches-to-a-regular-expression-in-python