【发布时间】:2016-08-07 23:24:42
【问题描述】:
我对正则表达式(正则表达式)相当陌生,需要一些帮助来制定字符串。我大部分都理解它,但是当我需要匹配的文本有变量后跟一个可选短语时,我感到很困惑。
假设文本的格式类似于“打开 $1 [the] 灯”,其中“$1”是我想要的变量,而“the”可以包含或省略。我尝试了以下简介,“turn (.+) (?:the)?\s*lights”,它适用于“打开灯”:
>>> re.match("turn (.+) (?:the)?\s*lights", "turn on lights").groups()
("on",)
但是当我包含“the”并尝试匹配“turn on the lights”时,我将“on the”作为我的变量。
>>> re.match("turn (.+) (?:the)?\s*lights", "turn on the lights").groups()
("on the",)
这可以通过正则表达式库来完成吗?如果问题不清楚,我深表歉意,在此先感谢您!
【问题讨论】:
标签: python regex variables optional-parameters optional-variables