匹配两组,但不应为空

2024-04-16 16:45:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望我的正则表达式能够匹配随机字符的字符串(可选地后跟一些数字),但是如果两个匹配都是空的,我希望匹配失败。我目前正在构建正则表达式,如下所示:

regex = u'^(.*)'
if has_digits: regex += u'(\d*)'
regex += ext + u'$' # extension group as in u'(\.exe)'
rePattern = re.compile(regex, re.I | re.U)

但它也匹配空文件名(仅具有扩展名)。不能把我的脑袋绕在类似的问题上,比如:

更复杂的是,第二组(数字)可能无法添加

如此有效:

abc%.exe
123.exe

如果has\数字为真:

abc 123.exe # I want the second group to contain the 123 not the first one

无效:.exe


Tags: orthe字符串reifgroupnot数字
2条回答

正则表达式:

^(.*?)(\d+)?(?<=.)\.exe$

正向向后看确保在扩展部分之前至少有一个字符。你知道吗

Live demo

综合:

regex = '^(.*?)'
if has_digits: regex += '(\d+)?'
regex += '(?<=.)' + ext + '$'
rePattern = re.compile(regex, re.I | re.U)

您可以使用这个基于lookahead的regex:

ext = r'\.exe'

regex = r'^(?=.+\.)(.*?)'
if has_digits: regex += r'(\d*)'
regex += ext + '$'
rePattern = re.compile(regex, re.I | re.U)
# ^(?=.+\.)(.*?)(\d*)\.exe$

RegEx Demo

Lookahead(?=.+\.)确保在点之前至少存在一个字符。你知道吗

相关问题 更多 >