RegEx 在有换行符的两个字符串之间获取字符串 [英] RegEx Get string between two strings that has line breaks

查看:48
本文介绍了RegEx 在有换行符的两个字符串之间获取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的班级:测试数据
测试部分:<br>我的部分
我的第 2 节
</td>

我试图在测试部分:和我的部分之后"之间获取文本

我尝试了几次不同的 RegEx 模式,但一无所获.

如果我这样做:

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

然后我得到了正确的回应:

' 部分:'

但是,如果我这样做

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

我没有得到任何结果.结果应该是我的部分
我的部分2
"

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

任何帮助将不胜感激.

如果重要的话,我正在用 Python 2.7 编码.

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

解决方案

使用 re.Sre.DOTALL 标志.或者在正则表达式前加上 (?s) 使 . 匹配所有字符(包括换行符).

没有标志,. 不匹配换行符.

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

<小时>

示例:

<预><代码>>>>s = '''... 我的课程:测试数据
... 测试部分:<br>...我的部分<br>... 我的第 2 部分
... </td>'''>>>>>>进口重新>>>re.findall('(?<=Test)(.*?)(?=</td>)', s) # 没有标志[]>>>re.findall('(?<=Test)(.*?)(?=</td>)', s, flags=re.S)[' 部分:
\n 我的部分
\n 我的部分 2
\n ']>>>re.findall('(?s)(?<=Test)(.*?)(?=)', s)[' 部分:
\n 我的部分
\n 我的部分 2
\n ']

I have the following test (formatted just like below):

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

I'm attempting to get the text between "Test Section: and the after the MY SECTION

I've tried several attempts with different RegEx patterns and I'm not getting anywhere.

If I do:

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

Then I get the correct response of:

' Section: '

But, if I do

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

I get no results. The results should be "MY SECTIon
MY SECTION 2
"

I've tried using RegEx Multiline as well with no results.

Any help would be appreciated.

If it matters I'm coding in Python 2.7.

If something is not clear, or you need more info, please let me know.

解决方案

Use re.S or re.DOTALL flags. Or prepend the regular expression with (?s) to make . matches all character (including newline).

Without the flags, . does not match newline.

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


Example:

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

这篇关于RegEx 在有换行符的两个字符串之间获取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆