如何匹配多线和单线

时间:2015-07-04 00:04:34

标签: python regex python-2.7

我正试图绕过一些正则表达式(使用Python 2.7)并且遇到了令人困惑的障碍。这与(。*)有关。我知道除非你使用标签re.DOTALL,否则dot会匹配除新行之外的所有内容。但是当我使用标签时,它包含太多。以下是我尝试过的一些变体和结果的代码:

import re
from urllib2 import urlopen
webpage = urlopen('http://trev.id.au/testfiles/rgxtxt.php').read()

# find the instances of pattern in the file
findPatHTMLComment = re.findall('<!--(.*)-->',webpage) 
foundItems = len(findPatHTMLComment) # how many instances where found?
# Print results
print "Found " + str(foundItems) + " matches. They are: "
listIterator = []
listIterator[:]=range(0,foundItems)
for i in listIterator:
    print "HTML_Comment["+ str(i) +"]: |" + findPatHTMLComment[i] + "| END HTML Comment"

这导致找到3个匹配项,因为它找不到多行注释部分。

使用:

findPatHTMLComment = re.findall('<!--(.*)-->',webpage,re.DOTALL)

使用文档末尾的第一个匹配查找单个匹配项。

findPatHTMLComment = re.findall('<!--(.*)-->',webpage,re.MULTILINE)

查找与第一个相同的内容,文件中的5个注释中只有3个。

问题:在这个例子中我应该使用什么作为正则表达式?你能为我和其他人解释一下吗?

感谢您提供的任何指导。谢谢你,祝你有个愉快的一天。

编辑:包含上面代码中链接的示例数据(将很快从服务器中删除样本数据):

<html>
<!--[if lt IE 9 ]>
    <script type="text/javascript">
        jQuery(function ($) {
            function TopSearchIE9(input,inputBtn){
                var $topSearch=$(input);
                var $topSearchBtn=$(inputBtn);
                $topSearch.keydown(function(e) {
                    if (e.keyCode == 13) {
                        $topSearchBtn.trigger("click");
                        return false;
                    }
                });
            }
            TopSearchIE9(".J-txt-focus1",".J-txt-focus1-btn");
            TopSearchIE9(".J-txt-focus2",".J-txt-focus2-btn");
        });
    </script> 
<![endif]-->
<!--[if lt IE 10 ]>
    <style>
        .new-header-search .hdSch-txt{ width: 225px;}
        .new-header-search .hdSch-del{width: 0px; padding: 5px 0px;}
        .new-header-search .hdSch-del.del{background:none; padding: }
    </style>
<![endif]-->
<body>
    <!-- This is a text file with a number of items to allow testing of some regex methods. It has no actual meaning -->
    <div head1>Item heading for first item</div>
    <!--By the way, this is a comment in a block of HTML text.-->
    <div itembody>We can jump over the moon if we are fast enough, but we really shouldn't try it cause we may get a blood nose. When we do try and succeed it feels quite good.</div>
    <div head1>Item heading for second item</div>
    <div itembody>If this is showing, its the second body within the itembody div tags for this file</div>
    <div head1>Item heading for the third item</div>
    <div itembody>
        Going to add another div tag 
        <div highlight>
            and closing div tag
        </div> 
        in this body to see how it handles that.
    </div>
    <!-- The above itembody data should 
        have it's own div and closing div tags -->
    <div head1>Item heading for the fourth item</div>
    <div itembody>
        <p><a href="mailto:fred@flinstone.com">email fred</a> or phone him on +63 493 3382 3329 when you are ready to try more regex stuff.</p>
        <p>You can also check with Barney by <a href="mailto:barney@rubble.com">emailing him</a> or phone him of +44 394 394 3992 if that is easier</p>
    </div>
    <!-- Thats all folks... -->
</body>

1 个答案:

答案 0 :(得分:9)

  

但是当我使用标签时,它包含太多。

*greedy运算符,意味着它将尽可能多地匹配,并且仍然允许正则表达式的其余部分匹配。您需要使用*运算符和?进行非贪婪匹配,这意味着“零或更多 - 最好尽可能少”。

re.findall('<!--(.*?)-->', webpage, re.DOTALL)
                   ↑

re.MULTILINE标志称为多行,因为锚点^$在实现时会在多行上运行,在这种情况下使用多行修饰符是多余的。 / p>

另一方面,我会考虑使用BeautifulSoup来完成这项任务。

from bs4 import BeautifulSoup, Comment
soup = BeautifulSoup(html)
comments = soup.find_all(text=lambda text:isinstance(text, Comment))
相关问题