【发布时间】:2016-10-05 21:14:58
【问题描述】:
我希望我的正则表达式能够匹配随机字符的字符串(可选地后跟一些数字) - 但如果两个匹配项均为空,我希望匹配失败。我目前正在构建正则表达式:
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
【问题讨论】:
-
你不能用
+替换*运算符吗? -
@FedericoPiazza 否,因为即使 has_digits 为真,数字也可能不存在 - 如果 has_digits 为真,则第一组是可选的 如果有一些数字
-
你能展示一些有效/无效的样本匹配吗?
-
@Tim 组因 has_digits 而异
-
@revo: 这不是说它会匹配
.exe吗?那不是?使第一个匹配成为可选的吗?
标签: python regex python-2.7 regex-lookarounds