我对 regex(正则表达式)相当陌生,需要一些关于制定字符串的帮助。我大部分都理解它,但当我需要匹配的文本有变量后跟一个可选短语时,我被难住了。
假设文本的格式类似于“turn $1 [the] lamp”,其中“$1”是我想要的变量,而“the”可以包含或省略。我尝试过以下简介“turn (.+) (?:the)?\s*lights”,它适用于“打开灯”:
>>> re.match("turn (.+) (?:the)?\s*lights", "turn on lights").groups()
("on",)
但是当我包含“the”并尝试匹配“turn on the lamp”时,我得到“on the”作为我的变量。
>>> re.match("turn (.+) (?:the)?\s*lights", "turn on the lights").groups()
("on the",)
这可以通过正则表达式库来完成吗?如果问题不清楚,我深表歉意,先谢谢您!
最佳答案
关于python - 具有连续变量的正则表达式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36656446/