栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

正则表达式-python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

正则表达式-python

https://www.runoob.com/python/python-reg-expressions.html
re.match函数

re.match尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回None。
函数语法:re.match(pattern, string, flags=0)

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
 
import re


print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配


print(re.match('com', 'www.runoob.com'))         # 不在起始位置匹配

'''
(0, 3)

None

'''

re.search方法

re.search扫描整个字符串并返回第一个成功的匹配。
函数语法:re.search(pattern, string, flags=0)

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
 
import re

print(re.search('www', 'www.runoob.com').span())  # 在起始位置匹配


print(re.search('com', 'www.runoob.com').span())         # 不在起始位置匹配

'''
(0, 3)  第0位到第2位

(11, 14) 第11位到第13位 含标点

'''

正则表达式修饰符 - 可选标志
正则表达式可以包含一些可选标志修饰符来控制匹配的模式。修饰符被指定为一个可选的标志。多个标志可以通过按位 OR(|) 它们来指定。如 re.I | re.M 被设置成 I 和 M 标志:

re.I
使匹配对大小写不敏感
re.L
做本地化识别(locale-aware)匹配
re.M
多行匹配,影响 ^ 和 $
re.S
使 . 匹配包括换行在内的所有字符
re.U
根据Unicode字符集解析字符。这个标志影响 w, W, b, B.

Group()例子多次尝试:

#!/usr/bin/python
import re
 
line = "Cats are smarter than dogs"
#------------------------------------------------------------------------
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
 
if matchObj:
   print ("matchObj.group() : ", matchObj.group())
   print ("matchObj.group(1) : ", matchObj.group(1))
   print ("matchObj.group(2) : ", matchObj.group(2))
   
   #print ("matchObj.group(3) : ", matchObj.group(3)) #IndexError: no such group
else:
   print ("No match!!")

'''
matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter

'''
#------------------------------------------------------------------------
matchObjj = re.match( r'(.*) are (.*) (.*)', line, re.M|re.I)

if matchObjj:
    
   print ("matchObj.group() : ", matchObjj.group())
   print ("matchObj.group(1) : ", matchObjj.group(1))
   print ("matchObj.group(2) : ", matchObjj.group(2))
   
   print ("matchObj.group(3) : ", matchObjj.group(3))
   
else:
   print ("No match!!")
'''
matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter than
matchObj.group(3) :  dogs
'''
#------------------------------------------------------------------------
matchObjjj = re.match( r'(.*) are (.*?) (.*)', line, re.M|re.I)

if matchObjjj:
    
   print ("matchObj.group() : ", matchObjjj.group())
   print ("matchObj.group(1) : ", matchObjjj.group(1))
   print ("matchObj.group(2) : ", matchObjjj.group(2))
   
   print ("matchObj.group(3) : ", matchObjjj.group(3))
   
else:
   print ("No match!!")
'''
matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter
matchObj.group(3) :  than dogs
'''
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/588100.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号