python正则表达式 学习记要

正则表达式

正则表达式的作用无非就是两个,一个是找到你想要的字符串,一个就是对字符串操作。对字符串操作的前提就是找到字符串,所以正则表达式的重点在于如何找到你想要的字符串。
所以学习正则表达式的一大部分是学习对“你想要的字符串”进行描述,为了让计算机能知道。等你描述完毕,计算机(正则表达式引擎)就可以去为你服务了。再扔给它一大长串字符串,让它找出你想要的信息吧。
那么,如何描述你想要的字符串(为了让引擎能懂)就是一个重点。描述方法如下:
字符有: . \d(digtal) \D \s(space) \S \w(word) \W
字符集有: [ abxy] [a-c] [ ^ab ]
描述数量: * 任意次 + 正数次 ?最多1次 {m,n} m-n次
描述位置: ^ 开头 $ 末尾 \A 字符串开头 \Z 字符串末尾
逻辑关系: | ()
分组匹配: () ()\1 用数字指定分组 ( ?P<> )给分组起名字 ()( ?=id ) 以分组的形式引用分组
若想了解详情,再附一张详情表:
正则表达式规则表

Python实现方式

正则表达式只是一种算法级的产品,到了各个语言里,语言要自己实现。下面简介python的实现方法。
- re模块,相当于正则表达式引擎,里面有各种组件
- 对于用户的描述信息,有pattern类,可以通过re的compile方法得到实例
- parttern包含如下信息:pattern:你的字符串描述,groups:表达式中的分组数量;
- 有了描述信息,就可以查找了,配有match类用来查找
* match类有如下信息:string:你扔给它的文本,re:你的pattern对象,pos,endpos:你希望在文本的位置中查找,lastindex,lastgroup:你找的字符串的位置或别名,可能为None。
* match有如下方法用于处理上述信息:
* match方法
* match是re的方法,要带上pattern;
* match也是pattern的方法

import re
m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')

print "m.string:", m.string
print "m.re:", m.re
print "m.pos:", m.pos
print "m.endpos:", m.endpos
print "m.lastindex:", m.lastindex
print "m.lastgroup:", m.lastgroup

print "m.group(1,2):", m.group(1, 2)
print "m.groups():", m.groups()
print "m.groupdict():", m.groupdict()
print "m.start(2):", m.start(2)
print "m.end(2):", m.end(2)
print "m.span(2):", m.span(2)
print r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3')

### output ###
# m.string: hello world!
# m.re: <_sre.SRE_Pattern object at 0x016E1A38>
# m.pos: 0
# m.endpos: 12
# m.lastindex: 3
# m.lastgroup: sign
# m.group(1,2): ('hello', 'world')
# m.groups(): ('hello', 'world', '!')
# m.groupdict(): {'sign': '!'}
# m.start(2): 6
# m.end(2): 11
# m.span(2): (6, 11)
# m.expand(r'\2 \1\3'): world hello!
  • search方法
  • search是re的方法,要带上pattern;
  • search也是pattern的方法
  • search返回的结果是bool
  • search用于查找信息很方便
  • 代码如下
pattern = re.compile(r'world') 

# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None 
# 这个例子中使用match()无法成功匹配 
match = pattern.search('hello world!') 

if match: 
    # 使用Match获得分组信息 
    print match.group() 

### 输出 ### 
# world
  • sub函数
  • re有一个,pattern有一个
  • 给它一个repl字符串,将所有想要的替换的位置换成repl
import re

p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'

print p.sub(r'\2 \1', s)

def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()

print p.sub(func, s)

### output ###
# say i, world hello!
# I Say, Hello World!

martch和search的区别
match是从字符串的起点开始做匹配,而search是从字符串做任意匹配。
注意:当正则表达式是’ ^ ‘开头时,match与search是相同的。match只有当且仅当被匹配的字符串开头就能匹配 或 从pos参数的位置开始就能匹配 时才会成功。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章