Python re模塊

jopen 8年前發布 | 7K 次閱讀 Python開發

閑話不多,走一遍簡單的代碼!

 

#encoding=utf-8
import  re
s = "My Name is Candy!"
print re.findall("\\b\w.+$",s)
print re.findall("^\w.+$",s) 
結果:
C:\Python27\python.exe D:/ProjectSpace/file-example.py
['My Name is Candy!']
['My Name is Candy!']
Process finished with exit code 0

 

\w  : 匹配任意數字、字母、下劃線

\W:  匹配任意非數字、字母、下劃線

\b : 匹配字符串開頭或結尾

\B : 匹配字符串開頭或結尾

\s : 匹配空白符

\S : 匹配非空白符

\d : 匹配任意數字

\D: 匹配任意數字

 

有了以上知識,我們下面就直接走幾個例子!

 

 

匹配字符串內包含 Candy 或者的地方

#encoding=utf-8
import re


s = "My Name is Candy!"
print  re.findall("Candy|!",s) 



結果:

C:\Python27\python.exe D:/ProjectSpace/file-example.py
['Candy', '!']
Process finished with exit code 0

 

匹配字符串內所有內容

 

#encoding=utf-8
import  re





s = """
My Name is Candy!
Welcome To My Home!
Are You ok?
"""



print  re.findall("\\b\w.+\\b",s)


結果:
C:\Python27\python.exe D:/ProjectSpace/file-example.py
['My Name is Candy', 'Welcome To My Home', 'Are You ok']
Process finished with exit code 0

 

 匹配字符串內所有以問號結尾的內容

 

#encoding=utf-8
import  re



s = """
My Name is Candy!
Who tell You My Name?
Welcome To My Home!
Are You ok?
"""




for i in re.findall("(.+\?\n)",s):
    print  re.sub("\\n.?",'',i)
    
    
結果:
C:\Python27\python.exe D:/ProjectSpace/file-example.py
Who tell You My Name?
Are You ok?
Process finished with exit code 0

 

 

 匹配字符串內所有以‘W’開頭的行的內容

 

#encoding=utf-8
import  re




s = """
My Name is Candy!
Who tell You My Name?
Welcome To My Home!
Are You ok?
"""



for i in re.findall("\\bW.+",s):
    print i

結果:    
C:\Python27\python.exe D:/ProjectSpace/file-example.py
Who tell You My Name?
Welcome To My Home!
Process finished with exit code 0

 

匹配字符串內所有包含‘My’的行的內容

 

#encoding=utf-8
import  re





s = """
My Name is Candy!
Who tell You My Name?
Welcome To My Home!
Are You ok?

"""




for i in re.findall(".*My.+",s):
    print i

結果:
C:\Python27\python.exe D:/ProjectSpace/file-example.py
My Name is Candy!
Who tell You My Name?
Welcome To My Home!
Process finished with exit code 0

 

哎! 半夜三更發的帖子, 今天就到這吧! 此處列舉的也許不是最好的匹配方法,大家可以自己進行嘗試。

來自: http://my.oschina.net/CandyMi/blog/596627

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!