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']

相關文章
相關標籤/搜索