正则表达式获取两个字符串之间的换行内容

11 投票
2 回答
19391 浏览
提问于 2025-04-18 14:06

我有一个测试,格式如下:

<td scope="row" align="left">
      My Class: TEST DATA<br>
      Test Section: <br>
      MY SECTION<br>
      MY SECTION 2<br>
    </td>

我想提取“Test Section:”和“MY SECTION”之间的文本。

我尝试了几种不同的正则表达式,但都没有成功。

如果我这样做:

(?<=Test)(.*?)(?=<br)

我得到了正确的结果:

' Section: '

但是,如果我这样做:

(?<=Test)(.*?)(?=</td>)

我没有得到任何结果。正确的结果应该是“MY SECTION
MY SECTION 2
”。

我也尝试过使用正则表达式的多行模式,但也没有结果。

如果有人能帮忙,我会非常感激。

顺便说一下,我是在用Python 2.7编程。

如果有什么不清楚的地方,或者你需要更多信息,请告诉我。

2 个回答

4

从索引1获取匹配的组

Test Section:([\S\s]*)</td>

在线演示

注意:根据你的需要修改最后一部分。

示例代码:

import re
p = re.compile(ur'Test Section:([\S\s]*)</td>', re.MULTILINE)
test_str = u"..."

re.findall(p, test_str)

模式解释:

  Test Section:            'Test Section:'
  (                        group and capture to \1:
    [\S\s]*                  any character of: non-whitespace (all
                             but \n, \r, \t, \f, and " "), whitespace
                             (\n, \r, \t, \f, and " ") (0 or more
                             times (matching the most amount
                             possible))
  )                        end of \1
  </td>                    '</td>'
23

使用 re.Sre.DOTALL 这两个选项。或者在正则表达式前面加上 (?s),这样 . 就可以匹配所有字符,包括换行符。

如果不使用这些选项,. 是无法匹配换行符的。

(?s)(?<=Test)(.*?)(?=</td>)

举个例子:

>>> s = '''<td scope="row" align="left">
...       My Class: TEST DATA<br>
...       Test Section: <br>
...       MY SECTION<br>
...       MY SECTION 2<br>
...     </td>'''
>>>
>>> import re
>>> re.findall('(?<=Test)(.*?)(?=</td>)', s)  # without flags
[]
>>> re.findall('(?<=Test)(.*?)(?=</td>)', s, flags=re.S)
[' Section: <br>\n      MY SECTION<br>\n      MY SECTION 2<br>\n    ']
>>> re.findall('(?s)(?<=Test)(.*?)(?=</td>)', s)
[' Section: <br>\n      MY SECTION<br>\n      MY SECTION 2<br>\n    ']

撰写回答