`
younglibin
  • 浏览: 1193245 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Python正则表达式十种相关的匹配方法

 
阅读更多

Python正则表达式需要各种各样的匹配,但是我们不能盲目的进行相匹配,下面就向大家介绍经常遇到的十种Python正则表达式匹配方式,希望大家有所收获。

1.测试Python正则表达式是否 匹配字符串的全部或部分

  1. regex=ur"..." #正则表达式  
  2. if re.search(regex, subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing() 

2.测试Python正则表达式是否匹配整个字符串

  1. regex=ur"...\Z" #正则表达式末尾以\Z结束  
  2. if re.match(regex, subject):  
  3. do_something()  
  4. else:  
  5. do_anotherthing() 

3. 创建一个匹配对象,然后通过该对象获得匹配细节

  1. regex=ur"..." #正则表达式  
  2. match = re.search(regex, subject)  
  3. if match:  
  4. # match start: match.start()  
  5. # match end (exclusive): match.end()  
  6. # matched text: match.group()  
  7. do_something()  
  8. else:  
  9. do_anotherthing() 

4.获取Python正则表达式所匹配的子串

 

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

5. 获取捕获组所匹配的子串

 

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

6. 获取有名组所匹配的子串

 

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

7. 将字符串中所有匹配的子串放入数组中

 

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

8.遍历所有匹配的子串

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

 

9.通过Python正则表达式 字符串创建一个正则表达式对象

  1. (Create an object to use the same regex for many 
    operations)  
  2. rereobj = re.compile(regex) 

 

10.用法1的Python正则表达式对象版本

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

以上就是对Python正则表达式相关问题匹配的解决方案。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics