非教程——僅供參考
以下內容只說明在Python
中如何使用正則表達式,對正則表達式本身不再說明,如果想了解正則表達式的話,可以參考這里。
模塊的函數 | 功能 |
---|---|
compile(pattern[, flags]) | 對正則表達式模式pattern進行編譯,flags是可選標識符,并返回一個regex對象 |
search(pattern, string[, flags]) | 在字符串string中搜索正則表達式模式pattern第一次出現,如果匹配成功,則返回一個匹配對象;否則返回None |
match(pattern, string[, flags]) | 用正則表達式模式pattern匹配字符串string,如果匹配成功,則返回一個匹配對象,否則返回None |
findall(pattern, string[, flags]) | 在字符串string中搜索正則表達式模式pattern的所有(非重復)出現;返回一個匹配對象的列表 |
finditer(pattern, string[, flags]) | 和findall()相同,但返回的不是列表而是迭代器;對于每個匹配,該迭代器返回一個匹配對象 |
split(pattern, string[, maxsplit=0, flags=0]) | 根據正則表達式pattern中的分隔符把字符string分割為一個列表,返回成功匹配的列表,最多分割max次(默認分割所有匹配的地方) |
sub(pattern, repl, string[, count, flags]) | 把字符串string中所有匹配正則表達式pattern的地方替換成字符串repl,如果max的值沒有給出,則對所有匹配的地方進行替換 |
subn(pattern, repl, string[, count, flags]) | 跟sub相同,但返回一個包含替換次數的元組tuple (new_string, number_of_subs_made). |
匹配對象的函數 | 功能 |
group([group1, ...]) | 返回全部或部分匹配對象 |
groups([default]) | 返回包含所有匹配對象的元組 |
以下是一個簡單的示例文件:
import re
#compile()用法示例
pattern='bat|bet|bit'
prog = re.compile(pattern)
result = prog.match('bat')
result = re.match(pattern, 'bat')
if result is not None:
print(result.group())
#macth()用法示例
m=re.match('foo','foo')#模式匹配字符串
if m is not None: #如果成功,顯示匹配
print ('匹配成功')
print (m.group())
else:
print ('匹配失敗')
m=re.match('foo','sfoo')#模式匹配字符串
if m is not None: #如果成功,顯示匹配
print ('匹配成功')
print (m.group())
else:
print ('匹配失敗')
#search()用法示例
m=re.search('foo','sfoo')#模式匹配字符串
if m is not None: #如果成功,顯示匹配
print ('搜索成功')
print (m.group())
else:
print ('搜索失敗')
#split()用法示例
m=re.split('\W+', 'Words, words, words.')
print(m)#['Words', 'words', 'words', '']
m=re.split('(\W+)', 'Words, words, words.')
print(m)#['Words', ', ', 'words', ', ', 'words', '.', '']
m=re.split('\W+', 'Words, words, words.', 1)
print(m)#['Words', 'words, words.']
m=re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
print(m)#['0', '3', '9']
#findall()用法示例
m=re.findall('car', 'carry the barcardi to the car')
print(m)#['car', 'car', 'car']
#sub()用法示例
m=re.sub('car','plane', 'carry the barcardi to the car')
print(m)#planery the barplanedi to the plane
鑒于正則表達式本身是塊非常龐大的知識塊,所以本文只是簡單介紹了python中使用正則表達式去匹配字符串的方法,要想熟練使用這些方法,主要還是得先對正則表達式有一定的了解。