【发布时间】:2014-03-10 02:05:01
【问题描述】:
我需要一个正则表达式模式的帮助,它允许我执行以下操作,但我不太确定如何操作。
command, extra = re.search(SomeRegexPattern, string).groups() # or split it to be a list
Input: ".SomeCommand"
command, extra = "SomeCommand", "" # extra is "" because there was nothing that follows "SomeCommand"
Input: ".SomeCommand Some extra stuff"
command, extra = "SomeCommand", "Some extra stuff"
Input: ".SomeCommand Some really long text after SomeCommand"
command, extra = "SomeCommand", "Some really long text after SomeCommand"
注意 SomeCommand 是动态的,它实际上不是 SomeCommand
是否有使这成为可能的正则表达式?所以命令是一回事,命令之后的任何东西都分配给extra?
更新: 看来我还没有充分说明正则表达式应该做什么,所以我正在更新答案以提供帮助。
while True:
text = input("Input command: ")
command, extra = re.search(SomeRegexPattern, text).groups()
示例数据
# when text is .random
command = "random"
extra = ""
# when text is .gis test (for google image search.)
command = "gis"
extra = "test"
# when text is .SomeCommand Some rather long text after it
command = "SomeCommand"
extra = "Some rather long text after it"
工作正则表达式
command, extra = re.search("\.(\w+)( *.*)", text).groups() # modified zhangxaochen's answer just a tad and it works, don't forget to redefine extra as extra.strip()
【问题讨论】:
-
目前尚不清楚这种模式应该如何表现。为什么第二个示例从输出中删除
Some?为什么要删除期间?其他类型的主角也应该被删除吗?仅splitting 字符串会产生您可以使用的输出吗? -
@user2357112 打错了,我会编辑的
-
@user2357112 我忘了解决你关于前导字符和拆分的第二个问题,但我认为正则表达式比尝试拆分字符串更适合这个问题。至于前导字符,如果我理解正确,任何字符都应该可以工作,无论它是数字、字母、小数还是其他任何字符。
标签: python regex python-3.x