美文网首页
python正则表达式

python正则表达式

作者: 蜀山客e | 来源:发表于2020-08-19 14:28 被阅读0次

在做接口的时候,上个接口返回的数据做为下一个接口的参数,这个时候我们可以用到正则表达式进行提取

正则表达式

正则表达式(regular expression)描述了一种字符串匹配的模式,可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

正则表达式常用字符

re模块

在python语言中正则表达式是通过re模块进行实现的

re模块常用方法

re.match(pattern, string, flags=0)

# match用法
re.match(pattern, string, flags=0)

a = 'foo'
b= 'foo '
m = re.match(a,b)   # 模式匹配字符串,匹配就返回信息,不匹配就返回None,如果从开始匹配,匹配到就返回。
print(m)
if m is not None:   # 如果匹配,就返回匹配内容
    print(m.group())

执行结果:

<re.Match object; span=(0, 3), match='foo'>
foo

group()表示返回匹配对象

groups()表示返回包含唯一或者全部的元祖形式

search(pattern, string, flags=0)

# search用法
# search(pattern, string, flags=0)
a = 'foo'
b= 'seafood '
m = re.search(a,b)   # 搜索匹配字符串,匹配就返回信息,不匹配就返回None
print(m)
if m is not None:   # 如果匹配,就返回匹配内容
    print(m.group())

执行结果:
<re.Match object; span=(3, 6), match='foo'>
foo
match()和search区别

re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

findall(pattern, string, flags=0)

# findall用法
# re.findall(pattern, string, flags=0)
a = 'sea foo'
b= 'sea food '
m = re.findall(a,b)     # 进行匹配,发现匹配的返回一个列表,如果没有找到匹配的,则返回空列表
print(m)


代码结果:
['sea foo']

finditer(pattern, string, flags=0)

# finditer用法
# finditer(pattern, string, flags=0)
b= 's3eaf1oo2d '
m = re.finditer(r'\d',b)    # 返回内容存在一个迭代器中
for i in m:
    print(i.group())

代码结果:
3
1
2

sub(pattern, repl, string, count=0, flags=0)
subn(pattern, repl, string, count=0, flags=0)

# sub 和subn的用法
# sub(pattern, repl, string, count=0, flags=0)
# subn(pattern, repl, string, count=0, flags=0)
a = 'Anjing is  a test'
b = 'exploit'
m = re.sub('test',b,a)  # 搜索和替换,返回替换内容
m1 = re.subn('test',b,a)    # 搜索和替换,返回替换内容+替换总数字
print(m)
print(m1)

代码结果:
Anjing is  a exploit
('Anjing is  a exploit', 1)

两者区别,subn返回比sub多一个替换总数字

split(pattern, string, maxsplit=0, flags=0)

# split用法
# split(pattern, string, maxsplit=0, flags=0)
a = 'test1:test2:test3'
m = re.split(':',a) # 已:进行分割,并返回分割数据已列表展示
print(m)

代码结果:
['test1', 'test2', 'test3']

点赞关注~~了解更多,加入我们。642830685。群内免费领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!技术大牛解惑答疑,同行一起交流。


相关文章

  • 正则表达式

    Python正则表达式初识(一) Python正则表达式初识(二) Python正则表达式初识(三) Python...

  • 正则表达式

    Python:正则表达式Python:正则表达式

  • Python正则表达式指南

    Python正则表达式指南 本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达...

  • Python爬虫(十)_正则表达式

    本篇将介绍python正则表达式,更多内容请参考:【python正则表达式】 什么是正则表达式 正则表达式,又称规...

  • python正则表达式

    本篇将介绍python正则表达式,更多内容请参考:【python正则表达式】 什么是正则表达式 正则表达式,又称规...

  • [转]python正则表达式(一) 函数使用

    原文:python | 史上最全的正则表达式 更全的正则表达式处理函数:在python中使用正则表达式(一) 0....

  • Python正则表达式

    python正则表达式

  • Python正则表达式用法详解

    搞懂Python 正则表达式用法 Python 正则表达式 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一...

  • Python正则表达式指南

    本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达式标准库的完整介绍及使用示例...

  • Python处理正则表达式超时的办法

    title: Python处理正则表达式超时的办法tags: [python3, 正则表达式超时, re模块]da...

网友评论

      本文标题:python正则表达式

      本文链接:https://www.haomeiwen.com/subject/wngrjktx.html