匹配两组,但其中 none 组应该为空
Match two groups but none of them should be empty
我希望我的正则表达式能够匹配随机字符的字符串,可选地后跟一些数字 - 但如果两个匹配项都是空的,我希望匹配失败。我目前正在构建正则表达式,如下所示:
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)
但这也匹配空文件名(只有扩展名)。无法解决类似的问题,例如:
- In a regular expression, match one thing or another, or both
- Matching a group that may or may not exist
更复杂的是第二组(数字)可能无法添加
如此有效:
abc%.exe
123.exe
如果has_digits为真:
abc 123.exe # I want the second group to contain the 123 not the first one
无效:.exe
正则表达式:
^(.*?)(\d+)?(?<=.)\.exe$
正后视确保在扩展部分之前至少有一个字符。
综合:
regex = '^(.*?)'
if has_digits: regex += '(\d+)?'
regex += '(?<=.)' + ext + '$'
rePattern = re.compile(regex, re.I | re.U)
您可以使用这个基于前瞻性的正则表达式:
ext = r'\.exe'
regex = r'^(?=.+\.)(.*?)'
if has_digits: regex += r'(\d*)'
regex += ext + '$'
rePattern = re.compile(regex, re.I | re.U)
# ^(?=.+\.)(.*?)(\d*)\.exe$
先行 (?=.+\.)
确保在 DOT 之前至少存在一个字符。
我希望我的正则表达式能够匹配随机字符的字符串,可选地后跟一些数字 - 但如果两个匹配项都是空的,我希望匹配失败。我目前正在构建正则表达式,如下所示:
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)
但这也匹配空文件名(只有扩展名)。无法解决类似的问题,例如:
- In a regular expression, match one thing or another, or both
- Matching a group that may or may not exist
更复杂的是第二组(数字)可能无法添加
如此有效:
abc%.exe
123.exe
如果has_digits为真:
abc 123.exe # I want the second group to contain the 123 not the first one
无效:.exe
正则表达式:
^(.*?)(\d+)?(?<=.)\.exe$
正后视确保在扩展部分之前至少有一个字符。
综合:
regex = '^(.*?)'
if has_digits: regex += '(\d+)?'
regex += '(?<=.)' + ext + '$'
rePattern = re.compile(regex, re.I | re.U)
您可以使用这个基于前瞻性的正则表达式:
ext = r'\.exe'
regex = r'^(?=.+\.)(.*?)'
if has_digits: regex += r'(\d*)'
regex += ext + '$'
rePattern = re.compile(regex, re.I | re.U)
# ^(?=.+\.)(.*?)(\d*)\.exe$
先行 (?=.+\.)
确保在 DOT 之前至少存在一个字符。