pythonRegex1,pythonRegex

來源:互聯網
上載者:User

pythonRegex1,pythonRegex

使用Regex,需要匯入re這個模組

1 >>> import re2 >>> pattern=r'abc'3 >>> str='abcdefghijabc11111abc'4 >>> re.findall( pattern, str )5 ['abc', 'abc', 'abc']6 >>> 

r定義Regex的規則,這裡匹配abc這個字串

元字元([])匹配一個範圍

>>> str="abc afc awc">>> pattern=r"a[bfw]c">>> re.findall( pattern, str )['abc', 'afc', 'awc']>>> pattern=r"a[bf]w">>> re.findall( pattern, str )[]>>> pattern=r"a[bf]c">>> re.findall( pattern, str )['abc', 'afc']>>> 

^:以...開頭,用在中括弧裡面表示非(取反,或者說排除)

1 >>> import re2 >>> str="ghostwu:hi my name is ghostwu, nice to meet you!"3 >>> pattern=r"ghostwu"4 >>> re.findall( pattern, str )5 ['ghostwu', 'ghostwu']6 >>> pattern=r"^ghostwu"7 >>> re.findall( pattern, str )8 ['ghostwu']9 >>> 
1 >>> str="abc"2 >>> pattern=r"a[b]c"3 >>> re.findall( pattern, str )4 ['abc']5 >>> pattern=r"a[^b]c"6 >>> re.findall( pattern, str )7 []8 >>> 

$:以....結尾

>>> str="ghostwu:hi my name is ghostwu, nice to meet you! Hanmeimei: Hi,ghostwu">>> pattern=r"ghostwu">>> re.findall( pattern, str )['ghostwu', 'ghostwu', 'ghostwu']>>> pattern=r"ghostwu$">>> re.findall( pattern, str )['ghostwu']>>> 

$在中括弧中被當做普通的字串匹配

 1 >>> pattern=r"a[bcd$]" 2 >>> re.findall( pattern, 'ab' ) 3 ['ab'] 4 >>> re.findall( pattern, 'ac' ) 5 ['ac'] 6 >>> re.findall( pattern, 'ad' ) 7 ['ad'] 8 >>> re.findall( pattern, 'abe' ) 9 ['ab']10 >>> re.findall( pattern, 'a$' )11 ['a$']12 >>> 

逸出字元 \

 1 >>> str="^ghostwu ^ghostwu ^ghostwu" 2 >>> pattern=r"^ghostwu" 3 >>> re.findall( pattern, str ) 4 [] 5 >>> pattern=r"ghostwu" 6 >>> re.findall( pattern, str ) 7 ['ghostwu', 'ghostwu', 'ghostwu'] 8 >>> pattern=r"\^ghostwu" 9 >>> re.findall( pattern, str )10 ['^ghostwu', '^ghostwu', '^ghostwu']11 >>> 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.