前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python中的正则表达式

Python中的正则表达式

作者头像
Oceanlong
发布2018-07-03 13:16:08
6410
发布2018-07-03 13:16:08
举报

前言

正则表达式作为一种字符串匹配逻辑,在此不做赘述。本文的重点,并不是正则表达式,而是在Python中使用正则表达式。

Re模块

Python 自带了re模块,它提供了对正则表达式的支持。主要用到的方法列举如下

代码语言:javascript
复制
#返回pattern对象
re.compile(string[,flag])  
#以下为匹配所用函数
re.match(pattern, string[, flags])
re.search(pattern, string[, flags])
re.split(pattern, string[, maxsplit])
re.findall(pattern, string[, flags])
re.finditer(pattern, string[, flags])
re.sub(pattern, repl, string[, count])
re.subn(pattern, repl, string[, count])

举个例子

代码语言:javascript
复制
# -*- coding: utf-8 -*-
 
#导入re模块
import re
 
# 将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”
pattern = re.compile(r'hello')
 
# 使用re.match匹配文本,获得匹配结果,无法匹配时将返回None
result1 = re.match(pattern,'hello')
result2 = re.match(pattern,'helloo CQC!')
result3 = re.match(pattern,'helo CQC!')
result4 = re.match(pattern,'hello CQC!')

其中,只有result3会为false。

举个大例子

要求

获取糗事百科首页的所有jpg图片的url

code

代码语言:javascript
复制
import urllib2
import re

# create header
page = 1
url = 'http://www.qiushibaike.com/hot/page/' + str(page)
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
# get original page
request = urllib2.Request(url,headers = headers)
response = urllib2.urlopen(request).read()
# complie image and jpg tag
pattern = re.compile(r'<img\ssrc="//[^\s]*.jpg')
# find all out
result = re.findall(pattern, response)
# print result
if result:
    for r in result:
        index = len(r)
        print r[12:index]

else:
    print 'match none'
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.09.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • Re模块
  • 举个例子
  • 举个大例子
    • 要求
      • code
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档