前面我们说到了如何在Python正则表达式z中匹配中文,说到了另一种方法,这就是如何巧妙的使用Python正则表达式匹配模式的问题了
Python匹配模式
re.compile(strPattern[, flag]):
这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。 第二个参数flag是匹配模式,取值可以使用按位或运算符'|'表示同时生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)与re.compile('(?im)pattern')是等价的。
可选值有:
主要非英文语系字符范围
|
模式 |
名称 |
说明 |
re.I |
re.IGNORECASE |
忽略大小写(括号内是完整写法,下同) |
re.M |
MULTILINE |
多行模式,改变'^'和'$'的行为 |
re.S |
DOTALL |
点任意匹配模式,改变'.'的行为, 使".“可以匹配任意字符 |
re.L |
LOCALE |
使预定字符类 \w \W \b \B \s \S 取决于当前区域设定 |
re.U |
UNICODE |
使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性 |
re.X |
VERBOSE |
详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。以下两个正则表达式是等价的: |
具体参见如下代码
-
-
-
import re
-
import sys
-
import urllib2
-
-
-
-
def TestReChinese( ):
- reload(sys)
- sys.setdefaultencoding( "utf-8" )
-
-
- page = r
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- req = urllib2.Request("http://blog.csdn.net/gatieme/article/list/1")
- req.add_header("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")
-
- try:
- cn = urllib2.urlopen(req)
- page = cn.read( )
- unicodePage = page.decode("utf-8")
- cn.close( )
- except urllib2.URLError, e:
- print 'URLError:', e.code
- return
- except urllib2.HTTPError, e:
- print 'HTTP Error:' + e.reason
- return
-
-
- reHtml = r'<span class="link_title"><a href="(.*?)">\s*(.*?)\s*</a></span>.*?<span class="link_postdate">(.*?)</span>\s*<span class="link_view" title=".*?"><a href="(.*?)" title=".*?">.*?</a>(.*?)</span>\s*<span class="link_comments" title=".*?"><a href="(.*?)#comments" title=".*?" onclick=".*?">.*?</a>(.*?)</span>'
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- pattern = re.compile(reHtml, re.S)
- myItems = re.findall(pattern, unicodePage)
-
-
-
-
-
-
-
-
-
-
-
-
- print len(myItems)
-
- for item in myItems:
- urlTitle = item[0].replace("\n", "")
- urlView = item[3].replace("\n", "")
- urlComments = item[5].replace("\n", "")
-
-
-
-
-
- if (urlTitle == urlView) and (urlTitle == urlComments):
- print "#------------------------------------------------------"
- print "地址:", item[0].replace("\n", ""),
- print "标题:", item[1].replace("\n", ""),
- print "时间:", item[2].replace("\n", ""),
- print "阅读:", item[4].replace("\n", ""),
- print "评论:", item[6].replace("\n", "")
- print "#-----------------------------------------------------"
- print
- print
-
-
-
if __name__ == "__main__" :
-
-
- reload(sys)
- sys.setdefaultencoding("utf-8")
-
- TestReChinese( )
转载:http://blog.csdn.net/gatieme/article/details/43275077