【发布时间】:2020-03-12 18:44:30
【问题描述】:
给定一个测试字符串:
teststr= 'chapter 1 Here is a block of text from chapter one. chapter 2 Here is another block of text from the second chapter. chapter 3 Here is the third and final block of text.'
我想创建一个这样的结果列表:
result=['chapter 1 Here is a block of text from chapter one.','chapter 2 Here is another block of text from the second chapter.','chapter 3 Here is the third and final block of text.']
使用re.findall('chapter [0-9]',teststr)
我收到['chapter 1', 'chapter 2', 'chapter 3']
如果我想要的只是章节编号,那很好,但我想要章节编号加上直到下一个章节编号的所有文本。在最后一章的情况下,我想得到章号和一直到最后的文字。
尝试re.findall('chapter [0-9].*',teststr) 会产生贪婪的结果:
['chapter 1 Here is a block of text from chapter one. chapter 2 Here is another block of text from the second chapter. chapter 3 Here is the third and final block of text.']
我不擅长正则表达式,因此我们将不胜感激。
【问题讨论】:
-
pattern = re.compile(r'chapter (?:(?!\s+chapter \d+).)+')并使用pattern.findall -
您可以通过在开头添加一些不包含“章节”的文本来改进您的示例。要识别匹配项,必须“章后跟一个空格,一个或多个数字,然后至少有一个空格?“章”可以是“章”吗?这些问题源于您是根据单个示例提出问题的事实. 这很少使问题不明确。您需要用文字准确而明确地陈述您的问题,然后使用一个或多个示例进行说明...
-
..这是一个可能的问题陈述示例,旨在完整且明确(但只是我对您想要的内容的猜测):“我希望提取所有以 ' 开头的字符串[cC]hapter d+ ',其中 '[cC]' 表示一个 'c' 或一个 'C' 并且 'd+' 表示一个或多个数字,并以句点结尾,后跟零个或多个空格,然后是字符串或另一个字符串 '[cC]hapter d+ '"。
-
为了不区分大小写,
pattern = re.compile(r'(?i)chapter (?:(?!\s+chapter \d+).)+')然后使用matches = pattern.findall(teststr) -
也许
re.split(r'(?!^)(?=chapter \d)', teststr)就够了?见the Python demo。