美文网首页
正则_问号实现可选匹配

正则_问号实现可选匹配

作者: 测试媛617 | 来源:发表于2018-08-20 18:10 被阅读0次
    import re
    batRegex = re.compile(r'Bat(wo)?man')
    mo1 = batRegex.search('The Adventures of Batman')
    print(mo1.group())
    mo2 = batRegex.search('The Adventures of Batwoman')
    print(mo2.group())
    
    
    phone = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')
    mo3 = phone.search('my phone is 123-456-5678')
    print(mo3.group())
    mo4 = phone.search('my phone is 456-7890')
    print(mo4.group())
    
    结果是:
    Batman
    Batwoman
    123-456-5678
    456-7890
    

    相关文章

      网友评论

          本文标题:正则_问号实现可选匹配

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