python-Regex

來源:互聯網
上載者:User

標籤:尋找替換   指定   dal   line   word   成功   它的   替換   bsp   

字串是編程時涉及到的最多的一種資料結構,對字串進行操作的需求幾乎無處不在。比如判斷一個字串是否是合法的Email地址,雖然可以編程提取@前後的子串,再分別判斷是否是單詞和網域名稱,但這樣做不但麻煩,而且代碼難以複用。

Regex是一種用來匹配字串的強有力的武器。它的設計思想是用一種描述性的語言來給字串定義一個規則,凡是符合規則的字串,我們就認為它“匹配”了,否則,該字串就是不合法的。

python中的Regex的文法和元字字元:

模組

1、re.match(pattern,string,flags)   ==>從字串的開始位置匹配。

例如:

import re
a=‘dhddhfkjhsfd45sdkssl465461256sahgkdshglsahkj‘
b=re.match(‘dh‘,a)
if b:
print(b.group())
elif b==None:
print(‘沒有匹配成功!‘)

結果:

dh

 

2、re.findall(pattern,string,flags)   ==>搜尋整個字串並返回一個list。

例如:

import re
a=‘ahddhfkjhsfd45sdkssl465461256sahgkdshglsahkj‘
b=re.findall(‘ahd‘,a)
if b:
print(b)
elif b==None:
print(‘沒有匹配成功!‘)

結果:

[‘ahd‘]

 

3、re.searchl(pattern,string,flags)   ==>搜尋整個字串,找到第一個匹配值後就返回。

例如:

import re
a=‘dhddhfkjhsfd45sdkssl465461256sahgkdshglsahkj‘
b=re.search(‘dh‘,a)
if b:
print(b.group())
elif b==None:
print(‘沒有匹配成功!‘)

結果:

dh

 

 

4、re.sub(pattern, repl, string, count=0, flags=0) ==>用於替換字串中的匹配項。

參數解釋:

  • pattern : 正則中的模式字串。
  • repl : 替換的字串,也可為一個函數。
  • string : 要被尋找替換的原始字串。
  • count : 模式比對後替換的最大次數,預設 0 表示替換所有的匹配。

例如:

import re
a=‘axfdgdfds‘
b=re.sub(‘d‘,‘|‘,a)
if b:
print(b)
elif b==None:
print(‘沒有匹配成功!‘)

結果:

axf|g|f|s

 

 

5、re.compile(pattern,flags)  ==>就是對匹配格式進行了編譯,在程式執行時要更快。

例如:

a=‘fsgdssdggsdds‘

p=re.compile(‘d‘)

ma=p.findall(a)

print(ma)

結果:

[‘d‘, ‘d‘, ‘d‘, ‘d‘]

 

 

6、re.split(pattern,stirng,[,maxsplit])==》按照能夠匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。 

例如:

import re 

p = re.compile(r‘\d+‘)

print  p.split( ‘one1two2three3four4‘ ) 結果:[‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘‘]       如果字串的最後一位不是數字則返回[‘one‘, ‘two‘, ‘three‘, ‘four‘]      

python-Regex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.