码迷,mamicode.com
首页 > 编程语言 > 详细

python 基础 8.3 match方法和search方法

时间:2017-11-18 22:32:23      阅读:409      评论:0      收藏:0      [点我收藏+]

标签:reduce   sizeof   usr   findall   class   epc   .com   msu   匹配   

一,正则对象的split 方法
split(string[,maxsplit])
按照能够匹配的字串讲string 分割后返回列表。maxsplit 用于指定最大分割次数,不指定将全部分割。来查找符合对象的字字符.
 
 
 
#/usr/bin/python
#coding=utf-8
#@Time   :2017/11/18 20:52
#@Auther :liuzhenchuan
#@File   :re 的matche 和 seach.py
import re
 
print ‘正则的常用方法‘
a = re.compile(r‘\d‘)
print dir(a)
print ‘##‘*30 + \n
 
>>>
正则的常用方法
[‘__class__‘, ‘__copy__‘, ‘__deepcopy__‘, ‘__delattr__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘findall‘, ‘finditer‘, ‘flags‘, ‘groupindex‘, ‘groups‘, ‘match‘, ‘pattern‘, ‘scanner‘, ‘search‘, ‘split‘, ‘sub‘, ‘subn‘]
 
 
#1 match 方法--匹配 .match(string[,pos[,endpos]])
#string:匹配使用的文本
#pos:文本中正则比比表达式开始搜索的索引。及开始搜索 string 的下标
#endpos:文本中正则表达式结束搜索的索引
#如果不指定破损,默认从开头匹配,如果匹配不到,直接返回None
 
print ‘##match 匹配的应用‘
a = ‘hello world hello liu‘
#正则匹配除 hello world 与 hello liu
reg = re.compile(r‘((hello w.*)(hello l.*))‘)
result = reg.match(a)
print result.groups()
print ‘##‘*30+ \n
>>>
##match 匹配的应用
(‘hello world hello liu‘, ‘hello world ‘, ‘hello liu‘)
############################################################
 
 
 
print ‘##match 添加了起始位置和结束位置,match(str,2,)起始位置2,到最后结束‘
b = ‘aa‘ + a
print ‘字符串b为:‘+ b
result2 = reg.match(b,2,)
reg = re.compile(r‘((hello w.*)(hello l.*))‘)
print result2.groups()
print ‘##‘*15
 
>>>
##match 添加了起始位置和结束位置,match(str,2,)起始位置2,到最后结束
字符串b为:aahello world hello liu
(‘hello world hello liu‘, ‘hello world ‘, ‘hello liu‘)
##############################
 
print ‘#match写上起始位置与结束位置可以根据字符串b匹配除正则。或者用 \w 也可以匹配出‘
reg = re.compile(r‘\w*((hello w.*)(hello l.*))‘)
result3 = reg.match(b)
print result3.groups()
print ‘##‘*30
 
>>>
#match写上起始位置与结束位置可以根据字符串b匹配除正则。或者用 \w 也可以匹配出
(‘hello world hello liu‘, ‘hello world ‘, ‘hello liu‘)
############################################################
 
 
#正则对象 search() 方法
这个方法用于查找字符串中可以匹配成功的字串。从string的pos 下标处尝试匹配pattern,如果pattern结束时认可匹配,在返回一个match对象:若无法匹配,则将pos加1后重新尝试匹配,指导pos=endpos 时仍无法匹配范虎None
 
b = ‘aahello world hello liu‘
reg = re.compile(r‘((hello w.*)(hello l.*))‘)
result4 = reg.search(b)
print result4
print result4.groups()
 
>>>
<_sre.SRE_Match object at 0x037993E0>
(‘hello world hello liu‘, ‘hello world ‘, ‘hello liu‘)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

python 基础 8.3 match方法和search方法

标签:reduce   sizeof   usr   findall   class   epc   .com   msu   匹配   

原文地址:http://www.cnblogs.com/lzcys8868/p/7858125.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!