파이썬 3에서 정규식을 사용하는 데 문제가 있으므로 누군가가 나를 도울 수 있다면 기뻐할 것입니다. 다음과 같은 텍스트 파일이 있습니다.
Header A
text text
text text
Header B
text text
text text
Header C
text text
here is the end
내가하고 싶은 것은 헤더 사이에 텍스트 목록이 있지만 헤더 자체를 포함하는 것입니다. 이 정규식을 사용하고 있습니다.
re.findall(r'(?=(Header.*?Header|Header.*?end))',data, re.DOTALL)
결과는 여기
['Header A\ntext text\n text text\n Header', 'Header B\ntext text\n text text\n Header', 'Header C\n text text here is the end']
문제는 목록의 모든 항목 끝에 다음 헤더가 있다는 것입니다. 보시다시피 모든 헤더는 다음 헤더를 찾으면 끝나지만 마지막 헤더는 특정 방식으로 끝나지 않습니다.
정규 표현식을 사용하여 자체 텍스트를 하위 문자열로 포함하는 모든 헤더의 목록 (튜플이 아님)을 얻는 방법이 있습니까?
Header [^\n]*[\s\S]*?(?=Header|$)
데모를 참조하십시오.
https://regex101.com/r/iS6jF6/21
import re
p = re.compile(r'Header [^\n]*[\s\S]*?(?=Header|$)')
test_str = "Header A\ntext text\ntext text\nHeader B\ntext text\ntext text\nHeader C\ntext text\nhere is the end"
re.findall(p, test_str)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다