python里使用正则表达式的组匹配是否成功之后再自引用
发布日期:2021-07-01 05:09:20 浏览次数:2 分类:技术文章

本文共 2482 字,大约阅读时间需要 8 分钟。

在前面学习了通过名称或组号来引用本身正则表达式里的组内容,可以实现前后关联式的相等判断。如果再更进一步,比如当前面组匹配成功之后,就选择一种模式来识别,而不匹配成功又选择另外一种模式进行识别,这相当于if...else...语句的选择。我们来学习这种新的语法:(?(id)yes-expression|no-expression)。其中id是表示组名称或组编号, yes-expression是当组匹配成功之后选择的正则表达式,而no-expression 是不匹配成功之后选择的正则表达式。如下例子:
#python 3.6#蔡军生 #http://blog.csdn.net/caimouse/article/details/51749579#import readdress = re.compile(    '''    ^    # A name is made up of letters, and may include "."    # for title abbreviations and middle initials.    (?P
([\w.]+\s+)*[\w.]+ )? \s* # Email addresses are wrapped in angle brackets, but # only if a name is found. (?(name) # remainder wrapped in angle brackets because # there is a name (?P
(?=(<.*>$))) | # remainder does not include angle brackets without name (?=([^<].*[^>]$)) ) # Look for a bracket only if the look-ahead assertion # found both of them. (?(brackets)<|\s*) # The address itself: username@domain.tld (?P
[\w\d.+-]+ # username @ ([\w\d.]+\.)+ # domain name prefix (com|org|edu) # limit the allowed top-level domains ) # Look for a bracket only if the look-ahead assertion # found both of them. (?(brackets)>|\s*) $ ''', re.VERBOSE)candidates = [ u'Cai junsheng
', u'No Brackets first.last@example.com', u'Open Bracket
', u'no.brackets@example.com',]for candidate in candidates: print('Candidate:', candidate) match = address.search(candidate) if match: print(' Match name :', match.groupdict()['name']) print(' Match email:', match.groupdict()['email']) else: print(' No match')
结果输出如下:
Candidate: Cai junsheng <Cai.junsheng@example.com>
  Match name : Cai junsheng
  Match email: Cai.junsheng@example.com
Candidate: No Brackets first.last@example.com
  No match
Candidate: Open Bracket <first.last@example.com
  No match
Candidate: Close Bracket first.last@example.com>
  No match
Candidate: no.brackets@example.com
  Match name : None
  Match email: no.brackets@example.com

在这里,当name组出现时才会寻找括号< >,如果括号不成对就不匹配成功;如果name组不出现,就不需要括号,因此选择了另一个正则表达式。

深入浅出Numpy
 

Python游戏开发入门


你也能动手修改C编译器


纸牌游戏开发

五子棋游戏开发

RPG游戏从入门到精通

WiX安装工具的使用
俄罗斯方块游戏开发
boost库入门基础
Arduino入门基础
Unity5.x游戏基础入门
TensorFlow API攻略
TensorFlow入门基本教程
C++标准模板库从入门到精通 
跟老菜鸟学C++
跟老菜鸟学python
在VC2015里学会使用tinyxml库
在Windows下SVN的版本管理与实战 
Visual Studio 2015开发C++程序的基本使用 
在VC2015里使用protobuf协议
在VC2015里学会使用MySQL数据库

转载地址:https://mysoft.blog.csdn.net/article/details/78543603 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python里使用正则表达式来替换匹配成功的组
下一篇:python里使用正则表达式的组匹配通过名称自引用

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月13日 12时16分41秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章