这个问题是关于在python中匹配先前定义的组...但它并不那么简单。
以下是我想要匹配的文字:
Figure 1: Converting degraded weaponry to research materials.
Converting degraded weaponry to research
materials.
这是我的正则表达式:
(Figure )(\d)(\d)?(: )(?P<description>.+)(\n\n)(?P=description)
现在,我目前的问题是正则表达式无法匹配文本,因为在第三行“研究”之后出现了换行符。我希望python在将前一个组与我的字符串匹配时忽略换行符。
答案 0 :(得分:0)
似乎有两种通用的方法:要么规范化文本(如jhermann所建议的那样),要么为每个可能的匹配运行一个函数/代码片段,并进行比单一算法更复杂的比较正则表达式。
。规范化:
text = re.sub(r"\n\n", somespecialsequence, text);
text = re.sun(r"\s*\n", " ", text);
text = re.sub(r"\s+", " ", text);
text = re.sub(somespecialsequence, "\n\n", text);
现在,这应该按预期工作:(Figure )(\d)(\d)?(: )(?P<description>.+)(\n\n)(?P=description)
或者,使用代码片段:
matches = re.finditer(r"(Figure )(\d+)(: )(.+)(\n\n)(.+)(?=Figure )", text, flags=re.S)
for m in matches:
text1 = m.group(4)
text2 = m.group(6)
text1 = re.sub("\W+", " ", text1)
text2 = re.sub("\W+", " ", text2)
if (text1 == text2):
// this is a match