自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python正則表達(dá)式如何匹配子串

開發(fā) 后端
Python正則表達(dá)式在進(jìn)行子串匹配的時候需要注意很多的問題,首先我們來看看如何獲取Python正則表達(dá)式中匹配的子串。

Python正則表達(dá)式有很多的時候需要我們進(jìn)行子串的匹配,不單在進(jìn)行替換的時候需要進(jìn)行,在很多的地方都會用到這些代碼。下面我們就來詳細(xì)的學(xué)習(xí)如何用Python正則表達(dá)式獲取自己想得到的匹配子串。

獲取Python正則表達(dá)式所匹配的子串(Get the part of a string matched by the regex)

 

  1. regex=ur"..." #正則表達(dá)式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. result = match.group()  
  5. else:  
  6. result = "" 

獲取捕獲組所匹配的子串(Get the part of a string matched by a capturing group)

 

  1. regex=ur"..." #正則表達(dá)式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. result = match.group(1)  
  5. else:  
  6. result = "" 

獲取有名組所匹配的子串(Get the part of a string matched by a named group)

 

  1. regex=ur"..." #正則表達(dá)式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. result = match.group("groupname")  
  5. else:  
  6. result = "" 

將字符串中所有匹配的子串放入數(shù)組中(Get an array of all regex matches in a string)

 

  1. reresult = re.findall(regex, subject) 

遍歷所有匹配的子串(Iterate over all matches in a string)

 

  1. for match in re.finditer(r"<(.*?)\s*.*?/\1>", subject)  
  2. # match start: match.start()  
  3. # match end (exclusive): match.end()  
  4. # matched text: match.group() 

通過Python正則表達(dá)式 字符串創(chuàng)建一個正則表達(dá)式對象(Create an object to use the same regex for many operations)

 

  1. rereobj = re.compile(regex) 

用法1的Python正則表達(dá)式對象版本(use regex object for if/else branch whether (part of) a string can be matched)

 

  1. rereobj = re.compile(regex)  
  2. if reobj.search(subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing() 

用法2的Python正則表達(dá)式對象版本(use regex object for if/else branch whether a string can be matched entirely)

 

  1. rereobj = re.compile(r"\Z")?。U齽t表達(dá)式末尾以\Z 結(jié)束  
  2. if reobj.match(subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing() 

以上就是對Python正則表達(dá)式在獲取匹配子串應(yīng)用的介紹。

【編輯推薦】

  1. Python字符串替換如何才能進(jìn)行字符的拆分
  2. Python文本亂碼發(fā)生時的解決方案
  3. Python編程語言總體性能優(yōu)點評測
  4. Python編程語言具有相當(dāng)高的適應(yīng)能力
  5. Python編程語言維和受到眾人的追捧
責(zé)任編輯:張浩 來源: CSDN
相關(guān)推薦

2009-09-16 16:22:04

正則表達(dá)式匹配

2009-09-16 17:02:15

正則表達(dá)式匹配字符串

2009-09-16 18:08:14

正則表達(dá)式匹配單詞

2010-07-21 10:43:25

Perl正則表達(dá)式匹配

2024-09-14 09:18:14

Python正則表達(dá)式

2021-01-27 11:34:19

Python正則表達(dá)式字符串

2010-03-10 18:57:53

Python正則表達(dá)式

2010-03-25 18:25:36

Python正則表達(dá)式

2018-09-27 15:25:08

正則表達(dá)式前端

2021-12-03 08:50:25

LeetCode正則表達(dá)式算法

2009-09-16 13:24:30

PHP正則表達(dá)式匹配

2009-09-16 16:48:03

正則表達(dá)式匹配數(shù)字

2009-08-14 17:44:46

C#中使用正則表達(dá)式匹

2020-09-04 09:16:04

Python正則表達(dá)式虛擬機(jī)

2010-03-04 15:20:20

Ubuntu Patt

2021-05-25 09:18:04

正則表達(dá)式Linux字符串

2010-03-15 16:13:11

Python正則表達(dá)式

2010-03-01 15:51:59

Python則表達(dá)式

2010-03-11 08:55:45

python正則表達(dá)式

2019-12-10 10:40:57

Python正則表達(dá)式編程語言
點贊
收藏

51CTO技術(shù)棧公眾號