简单介绍Python正则表达式(1)


python正则表达式学习,python正则是我们常用的计算机语言,应用非常广泛,下面的额文章就详细的介绍用python正则表达式来做一些复杂字符串分析,提取想要的信息够用就行,一下就是相关的详细的介绍。

正则表达式中特殊的符号:

“.” 表任意字符
“^ ” 表string起始
“$” 表string 结束
“*” “+” “?” 跟在字符后面表示,0个——多个, 1个——多个, 0个或者1个
*?, +?, ?? 符合条件的情况下,匹配的尽可能少//限制*,+,?匹配的贪婪性
{m} 匹配此前的字符,重复m次
{m,n} m到n次,m,n可以省略

举个例子 ‘a.*b’ 表示a开始,b结束的任意字符串
a{5} 匹配连续5个a

[] 表一系列字符 [abcd] 表a,b,c,d [^a] 表示非a
| A|B 表示A或者B , AB为任意的python正则表达式另外|是非贪婪的如果A匹配,则不找B
(…) 这个括号的作用要结合实例才能理解, 用于提取信息

  1. d [0-9]  
  2. D 非 \d  
  3. s 表示空字符  
  4. S 非空字符  
  5. \w [a-zA-Z0-9_]  
  6. \W 非 \w  
  7.  

一:re的几个函数

1: compile(pattern, [flags])
根据python正则表达式字符串 pattern 和可选的flags 生成正则表达式 对象生成正则表达式 对象见二)其中flags有下面的定义:

I 表示大小写忽略
L 使一些特殊字符集,依赖于当前环境
M 多行模式 使 ^ $ 匹配除了string开始结束外,还匹配一行的开始和结束
S “.“ 匹配包括‘\n’在内的任意字符,否则 . 不包括‘\n’
U Make \w, \W, \b, \B, \d, \D, \s and \S dependent on the Unicode character properties database
X 这个主要是表示,为了写正则表达式,更可毒,会忽略一些空格和#后面的注释

其中S比较常用应用形式如下

  1. import re  
  2. re.compile(……,re.S)  

2: match(pattern,string,[,flags])让string匹配,pattern,后面分flag同compile的参数一样返回MatchObject 对象

3: split( pattern, string[, maxsplit = 0])用pattern 把string 分开

  1. >>> re.split(‘\W+’, ‘Words, words, words.’)  
  2. ['Words', 'words', 'words', '']  

括号‘)’在pattern内有特殊作用,请查手册

4:findall( pattern, string[, flags])比较常用,从string内查找不重叠的符合pattern正则表达式的表达式,然后返回list列表

5:sub( pattern, repl, string[, count])repl可以时候字符串,也可以式函数当repl是字符串的时候,就是把string 内符合pattern的子串,用repl替换了当repl是函数的时候,对每一个在string内的,不重叠的,匹配pattern的子串,调用replsubstring),然后用返回值替换

  1. substringre.sub(r’def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):’,  
  2. … r’static PyObject*\npy_\1(void)\n{‘,  
  3. … ‘def myfunc():’)  
  4. ’static PyObject*\npy_myfunc(void)\n{‘  
  5. >>> def dashrepl(matchobj):  
  6. … if matchobj.group(0) == ‘-’: return ‘ ‘  
  7. … else: return ‘-’  
  8. >>> re.sub(‘-{1,2}’, dashrepl, ‘pro—-gram-files’)  
  9. ‘pro–gram files’  
  10.  

二:re的几个函数产生方式

通过 re.compile(pattern,[flags])回match( string[, pos[, endpos]]) ;返回string[pos,endpos]匹配pattern的MatchObject

  1. split( string[, maxsplit = 0])  
  2. findall( string[, pos[, endpos]])  
  3. sub( repl, string[, count = 0])  

这几个函数和re模块内的相同,只不过是调用形式有点差别re.几个函数和 正则表达式对象的几个函数,功能相同,但同一程序如果多次用的这些函数功能,正则表达式对象的几个函数效率高些


评论关闭