19 python正则表达式及相关函数

  1 1,正则表达式
  2 ########################################
  3 1,元字符
  4    . ^ $ * + ? {} [] \ |  ()
  5 
  6 "."    任意字符     
  7 "^"    字符串开始    '^hello'匹配'helloworld'而不匹配'aaaahellobbb'
  8 "$"    字符串结尾    与上同理
  9 "\\"    特殊字符转义或者特殊序列     
 10 []    表示一个字符集,匹配字符集中的一个字符
 11         [0-9]、[a-z]、[A-Z]、[^0]
 12         []中如果出现元字符,则元字符匹配意义失效,只作为普通字符
 13 
 14 "*" 0 个或多个字符(贪婪匹配)    <*>匹配<title>chinaunix</title>
 15 "+"    1 个或多个字符(贪婪匹配)    与上同理
 16 "?"    0 个或1个字符(贪婪匹配)    即可有可无
 17 {m}     对前一个字符重复m次,a{6}匹配6个a、a{2,4}匹配2到4个a
 18 {m,n}    对于前一个字符重复m到n次,
 19 {m,n}?    对于前一个字符重复m到n次,并取尽可能少    
 20        re.findall("a{2,4}?","aaaaaa")中 只会匹配2个
 21 
 22 
 23 
 24 "|"    或    A|B,或运算
 25 (...)    匹配括号中任意表达式     
 26 (?#...)    注释,可忽略     
 27 (?=...)    Matches if ... matches next, but doesn't consume the string.    '(?=test)'  在hellotest中匹配hello
 28 (?!...)    Matches if ... doesn't match next.    '(?!=test)'  若hello后面不为test,匹配hello
 29 (?<=...)     Matches if preceded by ... (must be fixed length).    '(?<=hello)test'  在hellotest中匹配test
 30 (?<!...)    Matches if not preceded by ... (must be fixed length).    '(?<!hello)test'  在hellotest中不匹配test
 31 
 32 #############################################
 33     正则表达式特殊序列表如下:
 34 \A    只在字符串开始进行匹配
 35 \Z    只在字符串结尾进行匹配
 36 \b    匹配位于开始或结尾的空字符串
 37 \B    匹配不位于开始或结尾的空字符串
 38 \d    相当于[0-9]
 39 \D    相当于[^0-9]
 40 \s    匹配任意空白字符:[\t\n\r\r\v]
 41 \S    匹配任意非空白字符:[^\t\n\r\r\v]
 42 \w    匹配任意数字和字母:[a-zA-Z0-9]
 43 \W    匹配任意非数字和字母:[^a-zA-Z0-9]
 44 
 45 ########################################################
 46 ##########      正则表达式的一些函数     ###############
 47 ########################################################
 48 python中re模块的用法
 49 
 50 Python 的 re 模块(Regular Expression 正则表达式)
 51 
 52 下面我主要总结了re的常用方法。
 53 1.re的简介
 54     使用python的re模块,python 会将正则表达式转化为字节码,利用 C 语言的匹配引擎进行深度优先的匹配。
 55 
 56 help(‘modules’)    ---查看python中已经安装好的模块
 57 import re          
 58 print re.__doc__   ##可以查询re模块的功能描述信息,即模块前面的注释
 59     下面会结合几个例子说明。
 60 
 61 ############################################
 62         i=patt.search(line)
 63         if i!=None:
 64             print line
 65         else:
 66             print "xxxx"
 67 
 68 
 69 1.re的主要功能函数
 70     常用的功能函数包括:compile、search、match、split、findall(finditer)、sub(subn)
 71     ##说明以下中括号,表示可有可无(即是可选参数)
 72 compile
 73      re.compile(pattern[, flags])
 74        作用:
 75           把正则表达式语法转化成正则表达式对象
 76      flags定义包括:
 77      re.I:忽略大小写
 78      re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境
 79      re.M:多行模式(如果要匹配的字符串是多行的话,即忽略换行符)
 80      re.S: 即’ . ’并且包括换行符在内的任意字符(注意:’ . ’不包括换行符)
 81             即增加了 '.'所能够匹配的范围
 82      re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库
 83      
 84 search  ##从整个字符串中匹配
 85     ##返回的也是个match对象或者空
 86     re.search(pattern, string[, flags])
 87     search (string[, pos[, endpos]])
 88     作用:在字符串中查找匹配正则表达式模式的位置,返回 MatchObject 的实例,如果没有找到匹配的位置,则返回 None。
 89 
 90 match    ##只匹配开头的
 91     ##返回的是一个match对象或者空
 92     re.match(pattern, string[, flags])
 93     match(string[, pos[, endpos]])
 94     作用:
 95     match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况,
 96     而 search() 函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用 search()。
 97 
 98 split
 99       ##返回字符串列表
100      re.split(pattern, string[, maxsplit=0, flags=0])
101      split(string[, maxsplit=0])
102      作用:可以将字符串匹配正则表达式的部分割开并返回一个列表
103 
104      例:
105         list1=re.split(r"ni","sssniaaanidddniiii")
106         print (list1)
107       结果为:
108         ["sss","aaa","ddd","iiii"]
109       例:
110         list1=re.split(r"(ni)","sssniaaanidddniiii")    ###注意正则表达式使用括号和不使用括号的区别 
111         print (list1)
112      结果为:
113          ["sss","ni","aaa","ni","ddd","ni","iiii"]
114 
115 
116 findall
117       ##返回匹配成功的字符列表或者空
118       re.findall(pattern, string[, flags])
119       findall(string[, pos[, endpos]])
120       作用:在字符串中找到正则表达式所匹配的所有子串,并组成一个列表返回
121       例:查找[]包括的内容(贪婪和非贪婪查找)
122       例:
123      a=re.findall(r"ni","woainidddni")
124      print (a)
125      结果为:["ni","ni"]     ##返回的是将匹配成功的字符串截取出来,返回,组成列表
126 
127 
128 finditer ()
129      ##返回的是一个迭代器(iterator)的对象或者空
130 
131 sub()/subn()
132     sub(正则,要替换成的字符,原始字符串)
133     例:
134      r=re.compile (r"a..b" )
135      a=r.sub("eee","ddaxybccc")
136      print (a)
137      >>ddeeeccc
138       --------
139      print ("#"*20)
140      rr=r"a..b"
141      a=re.sub(rr,"eeeeee","dddaxxbccc")
142      print (a)
143      >>dddeeeeeeccc
144      -----------
145      rr=r"a..b"
146      a=re.sub(rr,"","dddaxxbccc")
147      print (a)
148 
149      
150     说明:replace也是可以进行替换的,但是的参数并不是正则(因为replace参数不识别元字符)
151     
152 
153        
154 #######  例子: ########################
155 例:最基本的用法,通过re.RegexObject对象调用
156        #!/usr/bin/env python
157        import re
158        r1 = re.compile(r'world')       ##把“word”字符串,转化成正则表达式的对象,这样就可以调用正则表达式的其它函数了
159        if r1.match('helloworld'):      ##调用匹配函数
160            print 'match succeeds'
161        else:
162            print 'match fails'         ##因为是从位置0开始match所以,未匹配成功,
163 
164        if r1.search('helloworld'):
165            print 'search succeeds'      ##因为是搜索整个字符串进行匹配,所以会匹配成功
166        else:
167            print 'search fails'
168     说明:
169       以下执行结果为:
170       match fails
171       search fails
172 
173 说明一下:
174      r是raw(原始)的意思。因为在表示字符串中有一些转义符,如表示回车'\n'。如果要表示\表需要写为'\\'。但如果我就是需要表示一个'\'+'n',不用r方式要写为:'\\n'。但使用r方式则为r'\n'这样清晰多了。
175 
176 例:设置flag
177 
178      #r2 = re.compile(r'n$', re.S)
179      #r2 = re.compile('\n$', re.S)
180      r2 = re.compile('World$', re.I)    ##设置忽略大小写
181      if r2.search('helloworld\n'):      ##所以就可以匹配成功
182          print 'search succeeds'
183      else:
184          print 'search fails'
185      
186 例:直接调用
187 
188        if re.search(r'abc','helloaaabcdworldn'):
189            print 'search succeeds'
190        else:
191            print 'search fails'
192 
193    说明:
194       使用python是的正则表达式,
195       1,可以先 生成正则表达式对象
196       1.1,再使用该对象调用相应函数进行正则匹配
197 
198       2,可以直接使用正则表达式类,调用类中的方法,将正则表达式作为第一个参数,被匹配的作为第二个参数,
199 
200 #################################################################
201 4,正则分组
202     使用()
203     例:
204       匹配邮箱
205       email=r"\w{3}@\w+(\.com|\.cn)"
206       re.findall(email,"[email protected]")
207       re.findall(email,"[email protected]")
208 
209      注意:
210        如果正则中使用到分组,则返回的只有分组所匹配成功的数据(虽说匹配的有很多)
211        即优先返回分组所匹配的数据
212 
213      说明:
214        因为有时候,我们虽说匹配很多,但是我们只想要匹配出来字符串的某一段
215        此时只需使用()进行分组就好了

猜你喜欢

转载自www.cnblogs.com/2mei/p/9254211.html