Python——RegularExpressions正則表達式

以下是學習goole PYTHON教程過程中的一些筆記。
'#' 後面的是輸出,希望你能從中獲取你想要的。

Regular Expressions
import re
match = re.search(pat, text)     #match object

match = re.search('iig', 'called piiig')
#<_sre,SRE_Match  object  at  0xf7f7c448>
match.group()     #'iig'

match = re.search('igs', 'called piig')     #
match.group()     #error

def Find(pat, text):
   match = re.search(pat,text)
    if match: print match.group()
    else: print 'not found'

Find('ig', 'called piiig')
#ig
Find('hello', 'called piiig')
#not found

Find('...g', 'called piiig')
#iiig
Find('x...g', 'called piiig')
#not found
Find('..gs', 'called piiig')
#not found
Find('..g', 'called piig much better: xyzg')
#iig
Find('x..g', 'called piiig much better: xyzg')
#zyzg
Find(r'c\.l', 'c.lled piiig much better:xyzgs')
#c.l
Find(r':\w\w\w', 'blah :cat blah blah')
#cat
Find(r'\d\d\d', 'blah :123xxx ')
#123
Find(r'\d\s\d\s\d', '1 2 3')
#1 2 3
Find(r'\d\s+\d\s+\d', '1       2        3')
#1       2        3
Find(r':\w+', 'blah blah :kitten blabh blah')
#:kitten
Find(r':\w+', 'blah blah :kitten123 blabh blah')
#:kitten123
Find(r':\w+', 'blah blah :kitten123& blabh blah')
#:kitten123
Find(r':.+', 'blah blah :kitten123& blabh blah')
#blah blah :kitten123& blabh blah
Find(r':\S+', 'blah blah :kitten123&a=123&yatta  blabh blah')
#kitten123&a=123&yatta
Find(r'\w+@\w+', 'blah [email protected] yatta @ ')
#p@gmail
Find(r'[\w.]+@\w+', 'blah hi.[email protected] yatta @ ')
Find(r'\w[\w.]+@\w+', 'blah .[email protected] yatta @ ')
#nick.p@gmail
Find(r'\w[\w.]+@[\w.]+', 'blah .[email protected] yatta @ ')

m = re.search(r'([\w.]+)@([\w.]+)', 'blah [email protected] yatta @ ')
#<_sre.SRE_Match object at 0xF7F649F8>
m.group()
m.group(1)
#'nick.p'
m.group(2)
#'gmail.com'

re.findall(r'[\w.]+@[\w.]+', 'blah [email protected] yatta foo@bar ')
#['[email protected]', 'foo@bar']
re.findall(r'([\w.]+)@([\w.]+)', 'blah [email protected] yatta foo@bar ')
#[('nick.p', 'gmail.com'), ('foo', 'bar')]

.     #(dot) any char
\w     #word char
\d     #digit
\s     #whitespace
\S     #non-whitespace
+     #1 or more
*     #0 or more
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章