python库之re模块

首先:re库中有数组

__all__ = [ "match", "search", "sub", "subn", "split", "findall",
    "compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
    "U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
    "UNICODE", "error" ]

1.match:函数

    这个函数的意思是从头开始匹配,若是有将匹配上的数据返回,但只返回第一个,若是没有匹配上将返回None,注意,这个函数的弊端就是若是你要找的数据在中间的某个部分,它是不会返回值的,返回None。3d

pattern = re.compile('\d+')
str = 'bbb1234aaa5678'
m = pattern.match(str)

m=
None字符串

2.search:it

    为了解决上面的弊端,就出现了这个函数,这个函数能够从任何位置开始匹配,若是匹配上返回第一个数值,不然返回None。方法

pattern = re.compile('\d+')
str = 'bbb1234aaa5678'
n = pattern.search(str)

print n.group()error

# n=
# 1234数据

3.subword

    这个方法是被称做"替换"就是将你要替换的字段用其它的字段进行替换。pattern为匹配规则,strs使咱们要进行替换的字符串,m中的hello word 是咱们用它去替换咱们匹配的东西。co

pattern = re.compile('(\w+) (\w+)')
strs = 'hello 123, hello 456'
m = pattern.sub('hello word', strs)

print m

# hello word, hello word

4.subn

该函数返回的是一个数组,第一个参数是字符串,第二个参数是匹配成功的个数。

pattern = re.compile('(\w+) (\w+)')
strs1 = 'hello 123, hello 456'
m1 = pattern.subn('hello word', strs1)

匹配成功输出为:('hello word, hello word', 2)

strs2 = 'xxxxxxxxxxxxxx'
m2 = pattern.subn('hello word', strs2)

匹配失败输出为:('xxxxxxxxxxxxxx', 0)

5.split

根据模式的出现分割源字符串,返回包含结果子字符串的列表

pattern = re.compile('[\s\d\\\;]+')

m = pattern.split(r"a bb\aa;mm;     a")

# ['a', 'bb', 'aa', 'mm', 'a']

6.findall

匹配所有符合规则的字符串。

pattern = re.compile('\d+')
m = pattern.findall('12a3d4f5g678s9d0dawsasda')

# ['12', '3', '4', '5', '678', '9', '0']

相关文章
相关标签/搜索