【问题标题】:RegEx Get string between two strings that has line breaksRegEx 获取两个具有换行符的字符串之间的字符串
【发布时间】:2014-09-12 02:10:52
【问题描述】:

我有以下测试(格式如下):

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

我正在尝试获取“测试部分:和我的部分之后”之间的文本

我用不同的 RegEx 模式尝试了几次尝试,但都没有成功。

如果我这样做:

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

然后我得到正确的响应:

' Section: '

但是,如果我这样做了

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

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

我也尝试过使用 RegEx Multiline,但没有结果。

任何帮助将不胜感激。

如果重要的话,我正在使用 Python 2.7 进行编码。

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

【问题讨论】:

  • 我建议您使用解析器,具体取决于您使用的语言。

标签: python regex python-2.7


【解决方案1】:

使用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    ']

【讨论】:

  • 感谢您的好评!
【解决方案2】:

从索引 1 获取匹配组

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

Live demo

注意:根据需要更改最后一部分。

示例代码:

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>'

【讨论】:

  • 感谢您的好评!
猜你喜欢
  • 2015-06-24
  • 2016-07-12
  • 1970-01-01
  • 2012-12-28
  • 2014-04-27
  • 1970-01-01
  • 2013-09-14
相关资源
最近更新 更多