美文网首页
正则表达式-深入元字符

正则表达式-深入元字符

作者: 部落大圣 | 来源:发表于2018-10-09 18:58 被阅读8次

    元字符

    有些比较特殊的元字符是*,+,?{和},它们用来指定重复的次数。

    元字符*叫通配符,是匹配范围最广的模式之一,因为它可以匹配零个和多个任意字符(除了换行符:\r和\n),并且它们总是尝试尽可能多的匹配,匹配可以是一个字符,一个类或者括号中的一组字符。

    import re
    
    pattern = r"egg(spam)*"
    
    if re.match(pattern, "egg"):
        print("Match 1")
    
    if re.match(pattern, "eggspamspamegg"):
        print("Match 2")
    
    if re.match(pattern, "spam"):
        print("Match 3")
    ...........................................................
    Match 1
    Match 2
    

    示例匹配以egg开头的字符串后面跟随零或者多个spam的字符串
    总是尝试匹配尽可能多的模式叫做贪心模式。

    元字符+

    元字符+与*非常相似,只不过它的意思是一个或者多个重复,而不是零个和多个重复。

    import re
    pattern = r"g+"
    
    if re.match(pattern, "g"):
        print(" Match 1")
    if re.match(pattern, "ggggggggggg"):
        print(" Match 2")
    if re.match(pattern,"sda"):
        print("Match 3")
    ...................................................
    Match 1
    Match 2
    

    *匹配前面表达式的0次和多次。
    +匹配前面表达式的1次和多次。

    元字符?

    元字符?匹配0或者1个前面的重复

    import re
    
    pattern = r"ice(-)?cream"
    
    if re.match(pattern, "ice-cream"):  # 1次
        print(" Match 1 ")
    if re.match(pattern, "icecream"):  # 0次
        print(" Match 2 ")
    if re.match(pattern, "sausdasaeadg"):
        print(" Match 3 ")
    if re.match(pattern, "ice--ice"):  # 2次
        print(" Match 4 ")
    .....................................................
    Match 1
    Match 2
    

    花括号{}

    {}可以用来表示两个数字之间的重复次数。表达式{x,y}表示匹配次数介于x和y前面的字符。
    因此{0,1}和?的意思相同。
    如果不写第一个数字,它默认为零。如果不写第二个数字,它被认为是可以匹配很多次。

    import re
    
    pattern = r"9{1,3}$"
    
    if re.match(pattern, "9"):
        print(" Match 1")
    if re.match(pattern, "999"):
        print(" Match 2")
    if re.match(pattern, "9999"):
        print(" Match 3")
    .....................................................
    Match 1
    Match 2
    

    9{1,3}$匹配字符串含有1次到3次的9.
    注意在python里制定的数字必须小于4294967295且第一个必须小于等于第二个。

    4294967295的数值是 ,表示为二进制则为11111111111111111111111111111111(32个1),在运行32位64位系统的计算机中是无符号长整形数所能表示的最大值,亦是运行32位系统的计算机中所能表示的最大自然数(维基百科https://zh.wikipedia.org/wiki/4294967295

    相关文章

      网友评论

          本文标题:正则表达式-深入元字符

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