正则表达式匹配出现0次或一次

There are two more repeating qualifiers. The question mark character, ?, matches either once or zero times;
you can think of it as marking something as being optional.
For example, home-?brew matches either 'homebrew' or 'home-brew'.

import re

str_list = ["u_ex200331.log", "u_ex200331_x.log", "u_ex200331_xxx.log", "u_ex203888_x_x.log"]

matchObj = [str for str in str_list if re.match('^(u_ex[0-9]{6}(_x)?\.log)$', str)]

print(matchObj)

结果输出为:

['u_ex200331.log', 'u_ex200331_x.log']

posted @ 2020-04-16 10:07  东宫得臣  阅读(4379)  评论(0编辑  收藏  举报