2019-09-03 | 16818

更多模式字符

更多的模式字符是*,+,?,{}。 这些指定重复次数。 元字符*意味着“零或更多重复以前的事情”。它试图匹配尽可能多的重复。“以前的东西”可以是一个字符,一个类,或者一组字符在括号中。

例如:

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

结果:

>>>
匹配 1
匹配 2
>>>
上面的例子与以“鸡蛋”开头的字符串匹配,并跟随零次或更多的“spam”。

1

发表评论

    评价:
    Rich Text Editor
    最新评论