这个问题是关于在 python 中匹配先前定义的组......但它并不那么简单。
这是我要匹配的文本:
Figure 1: Converting degraded weaponry to research materials.
Converting degraded weaponry to research
materials.
这是我的正则表达式:
(Figure )(\d)(\d)?(: )(?P<description>.+)(\n\n)(?P=description)
现在,我目前遇到的问题是正则表达式无法匹配文本,因为换行符出现在第三行的“research”之后。我希望 python 在将前一组与我的字符串匹配时忽略换行符。
最佳答案
似乎有两种通用的方法:要么将文本规范化(如 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
关于python - 在 python 中匹配先前定义的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19548868/