import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import re
b = re.compile(r"\d+\.\d*")
match21 = b.match('3.1415')
match22 = b.match('33')
if match21:
# 使用match獲得分組資訊
print match21.group()
else:
u'match21不是小數'
if match22:
# 使用match獲得分組資訊
print match22.group()
else:
u'match22不是小數'
#若開頭不將編碼方式設為utf-8,此處變為unicode會報錯
import re
# 匹配如下內容:單詞+空格+單詞+任意字元
m = re.match(r'(\w+) (\w+)(?p.*)', 'hello world!')
"m.string:", m.string #匹配上使用的文字:hello world
"m.re:", m.re
"m.pos:", m.pos #文字中正規表示式開始搜尋的索引:0
"m.endpos:", m.endpos #正規表示式結束的索引:12
"m.lastindex:", m.lastindex #最後乙個**獲的分組在文中的索引:3
"m.lastgroup:", m.lastgroup #最後乙個**獲的分組的別名:sign
"m.group():", m.group() #不填寫引數相當於group(0),返回整個匹配的子串
"m.group(1,2):", m.group(1, 2) #('hello', 'world')
"m.groups():", m.groups() #以元組形式返回全部分組截獲的字串('hello', 'world', '!')
"m.groupdict():", m.groupdict() #返回以有別名的組的別名為鍵,以該組截獲的子串為值的字典:
"m.start(2):", m.start(2) #返回指定的組截獲的子串在string中的起始索引(子串第乙個字元的索引):6
"m.end(2):", m.end(2) #返回指定的組截獲的子串在string中的結束索引(子串最後乙個字元的索引+1):11
"m.span(2):", m.span(2) #返回(start(group), end(group)):(6,11)
r"m.expand(r'\g<2> \g<1>\g<3>'):", m.expand(r'\2 \1\3') #world hello!
#match&search演示
import re
# 將正規表示式編譯成pattern物件
pattern = re.compile(r'world')
# 使用search()查詢匹配的子串,不存在能匹配的子串時將返回none
# 這個例子中使用match()無法成功匹配
match = pattern.search('hello world!')
if match:
# 使用match獲得分組資訊
print match.group()
print match.span()
#結果如下:
world
(6, 11)
import re
p = re.compile(r'\d+')
print p.split('one1two2three3four4')
print p.findall('one1two2three3four4')
print p.search('one1two2three3four4').group()
結果如下:
['one', 'two', 'three', 'four', '']
['1', '2', '3', '4']
1
參考資料:#sub用法
import re
#p表示單詞字元、空格、單詞字元
p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world! barney'
print p.sub(r'\2 \1', s)
deffunc
(m):
return m.group(1).title() + ' ' + m.group(2).title() #使得字串首字母大寫
print p.sub(func, s)
#結果為:
say i, world hello! barney
i say, hello world! barney
正規表示式 正規表示式 總結
非負整數 d 正整數 0 9 1 9 0 9 非正整數 d 0 負整數 0 9 1 9 0 9 整數 d 非負浮點數 d d 正浮點數 0 9 0 9 1 9 0 9 0 9 1 9 0 9 0 9 0 9 1 9 0 9 非正浮點數 d d 0 0 負浮點數 正浮點數正則式 英文本串 a za z...
正規表示式 表示式
網域名稱 a za z0 9 a za z0 9 a za z0 9 a za z0 9 interneturl a za z s 或 http w w w 手機號碼 13 0 9 14 5 7 15 0 1 2 3 5 6 7 8 9 18 0 1 2 3 5 6 7 8 9 d 號碼 x x x...
Linux正規表示式 編寫正規表示式
為了所有實用化的用途,你可以通過使用程式產生正確的結果。然而,並不意味著程式總是如你所願的那樣正確地工作。多數情況下,如果程式不能產生想要的輸出,可以斷定真正的問題 排除輸入或語法錯誤 在於如何描述想要的東西。換句話說,應該考慮糾正問題的地方是描述想要的結果的表示式。表示式不完整或者公式表示得不正確...