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

开发 后端
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正则表达式相关问题匹配的解决方案。

【编辑推荐】

  1. 关于Python脚本语言进行学习介绍
  2. Python脚本在游戏中寻找自己的知音
  3. Python脚本在VIM环节中的系统介绍
  4. 利用Python脚本自动生成相应文件的解决方案
  5. Python脚本解决在游戏开发中的困难
责任编辑:张浩 来源: IT168
相关推荐

2010-03-10 18:57:53

Python正则表达式

2009-09-16 16:22:04

正则表达式匹配

2010-03-15 16:21:28

Python正则表达式

2009-11-30 17:22:24

PHP正则表达式多行匹

2009-09-16 18:08:14

正则表达式匹配单词

2009-09-16 13:24:30

PHP正则表达式匹配

2021-01-27 11:34:19

Python正则表达式字符串

2018-09-27 15:25:08

正则表达式前端

2009-08-14 17:44:46

C#中使用正则表达式匹

2010-03-18 12:40:47

python正则表达式

2010-03-25 18:25:36

Python正则表达式

2010-03-04 15:20:20

Ubuntu Patt

2009-09-16 13:53:17

PHP正则表达式匹配

2021-12-03 08:50:25

LeetCode正则表达式算法

2009-09-16 16:48:03

正则表达式匹配数字

2020-09-04 09:16:04

Python正则表达式虚拟机

2010-03-01 15:51:59

Python则表达式

2010-03-11 08:55:45

python正则表达式

2019-12-10 10:40:57

Python正则表达式编程语言

2020-11-04 09:23:57

Python
点赞
收藏

51CTO技术栈公众号