【问题标题】:Matching previously defined groups in python匹配python中先前定义的组
【发布时间】:2013-11-02 03:40:35
【问题描述】:

这个问题是关于匹配以前在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 在将前一个组与我的字符串匹配时忽略换行符。

【问题讨论】:

  • 这不是标准正则表达式中的东西,据我所知。试试 Python 的模糊匹配。
  • 我相信您可以使用re.MULTILINE 完成此任务。看看这是否有帮助:stackoverflow.com/questions/587345/…
  • 不幸的是,仅仅启用 re.MULTILINE 并没有帮助。
  • @Hoopdady 不,re.MULTILINE 只会导致 ^$ 锚点匹配每行的开头和结尾,而不是仅匹配字符串的开头和结尾。 docs.python.org/2/library/re.html#module-contents
  • 您必须事先以某种方式将文本规范化,才能使这种匹配起作用。一种可能性是textwrap

标签: python regex


【解决方案1】:

似乎有两种通用方法:要么规范化文本(如 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&lt;description&gt;.+)(\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

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 2012-04-26
    • 2022-12-04
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多