正则表达式,用于捕获内容并忽略换行符

时间:2019-06-02 20:29:03

标签: regex beautifulsoup regex-lookarounds regex-group regex-greedy

这是代码:

<!-- message --> 
<div><b><font size="6"><font color="Red">Bilim ve Teknik dergisi Mayıs 2019 Sayısı Pdf</font></font></b><br />
<br />
<img src="https://scontent-dus1-1.xx.fbcdn.net/v/t1.0-9/59069640_871111339894885_8805863518755618816_n.jpg?_nc_cat=109&amp;_nc_ht=scontent-dus1-1.xx&amp;oh=2a71d0bc34cda6b45404c30624c75046&amp;oe=5D6C1B30" border="0" alt="" /><br />
<br />
<b><font size="5"><a href="https://yadi.sk/i/oMnXUgBtTqKopg?fbclid=IwAR3KPXInlWCKFXuTKP1AU1VQGdsgvcDLdV9Px6YGOn3aU1tqAFz4Zo2J6PY" target="_blank">https://yadi.sk/i/oMnXUgBtTqKopg?fbc...1tqAFz4Zo2J6PY</a></font></b></div>
<!-- / message -->

我如何在<!-- message --><!-- message -->之间走?

我正在使用Python 3和BeautifulSoup4。 以下代码产生空的混乱值:

tl="58421"
topLink="https://www.eskikitaplarim.com/showthread.php?t="+tl
page=s.get(topLink)
psoup=bs(page.text,'html.parser')
mess=psoup.find_all(text=re.compile("<!-- message -->(.*?)<!-- \/ message -->"))
print(mess)

1 个答案:

答案 0 :(得分:0)

在这里,我们可以使用传递新行的表达式来获得所需的输出,例如:

<!-- message -->([\s\S]*)<!-- \/ message -->

Demo 1

或:

<!-- message -->([\d\D]*)<!-- \/ message -->
<!-- message -->([\w\W]*)<!-- \/ message -->

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"<!-- message -->([\s\S]*)<!-- \/ message -->"

test_str = ("<!-- message --> \n"
    "<div><b><font size=\"6\"><font color=\"Red\">Bilim ve Teknik dergisi Mayıs 2019 Sayısı Pdf</font></font></b><br />\n"
    "<br />\n"
    "<img src=\"https://scontent-dus1-1.xx.fbcdn.net/v/t1.0-9/59069640_871111339894885_8805863518755618816_n.jpg?_nc_cat=109&amp;_nc_ht=scontent-dus1-1.xx&amp;oh=2a71d0bc34cda6b45404c30624c75046&amp;oe=5D6C1B30\" border=\"0\" alt=\"\" /><br />\n"
    "<br />\n"
    "<b><font size=\"5\"><a href=\"https://yadi.sk/i/oMnXUgBtTqKopg?fbclid=IwAR3KPXInlWCKFXuTKP1AU1VQGdsgvcDLdV9Px6YGOn3aU1tqAFz4Zo2J6PY\" target=\"_blank\">https://yadi.sk/i/oMnXUgBtTqKopg?fbc...1tqAFz4Zo2J6PY</a></font></b></div>\n"
    "<!-- / message -->")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx电路

jex.im可视化正则表达式:

enter image description here