Python 匹配以某个字母开头的段落
我有一个包含以AB开头的段落的文件,我想得到所有这些段落, 我使用了以下代码,但它不返回任何内容:Python 匹配以某个字母开头的段落,python,regex,Python,Regex,我有一个包含以AB开头的段落的文件,我想得到所有这些段落, 我使用了以下代码,但它不返回任何内容: import re paragraphs = re.findall(r'AB[.\n]+AD',text) #AD is the beginning of the next paragraph 你知道为什么这不起作用吗 感谢pythonre模块文档中的: [] Used to indicate a set of characters. Characters can be listed
import re
paragraphs = re.findall(r'AB[.\n]+AD',text) #AD is the beginning of the next paragraph
你知道为什么这不起作用吗
感谢python
re
模块文档中的:
[]
Used to indicate a set of characters. Characters can be listed individually,
or a range of characters can be indicated by giving two characters and
separating them by a '-'. Special characters are not active inside sets.
这意味着括号内的
与点匹配,而不是与regexp中的任何其他字符匹配。请尝试:
re.findall(r'AB.+?(?=AD)', text, re.DOTALL)
re.DOTALL
标志将允许点覆盖包括换行符在内的所有内容。和(?=AD)
将匹配所有内容,直到AD
之前的最后一个字符,但不会将AD
包含到匹配的字符串中
然后,您可以rstrip()
生成的字符串以从末尾删除所有换行符