对正则表达式python的帮助

对正则表达式python的帮助,python,regex,python-3.x,Python,Regex,Python 3.x,我需要一个regex模式的帮助,它允许我做下面的事情,但我不太确定如何做 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"

我需要一个regex模式的帮助,它允许我做下面的事情,但我不太确定如何做

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

有没有一个正则表达式使这成为可能?因此,命令是一回事,命令之后的任何内容都被指定为额外的

更新: 似乎我还没有充分说明正则表达式应该做什么,所以我正在更新答案以提供帮助

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"
工作正则表达式

命令,extra=re.search(\.(\w+)(*.*),text.groups()#稍微修改了张晓晨的答案,结果很好,别忘了将extra重新定义为extra.strip()

类似的东西

In [179]: cmd = 'SomeCommand'

In [180]: s = '.SomeCommand Some extra stuff'

In [189]: command, extra = re.search(r'\.(%s)( *.*)'%cmd, s).groups()
     ...: print command, '----', extra.strip()
SomeCommand ---- Some extra stuff

In [190]: s = '.SomeCommand'

In [191]: command, extra = re.search(r'\.(%s)( *.*)'%cmd, s).groups()
     ...: print command, '----', extra.strip()
SomeCommand ---- 
编辑: 在更新时,您的命令似乎从不包含空格,因此只需使用
str.split
,maxslit为
1

In [212]: s = '.SomeCommand'

In [215]: s.split(' ', 1)
Out[215]: ['.SomeCommand']

In [216]: s = '.SomeCommand Some extra stuff'

In [217]: s.split(' ', 1)
Out[217]: ['.SomeCommand', 'Some extra stuff']
为避免解包错误(如果您坚持解包):


差不多了,但如果只有“.SomeCommand”呢?它给了我一个非类型错误,但几乎成功了。@user3234209如果您不知道该命令是什么,您如何识别它?给我们你的规则;)该命令是否包含空格?或者用双引号包装?@user3234209如果您的命令不包含空格,请参阅我的更新我编辑了答案以显示工作正则表达式。它只是您的一个修改版本,因此您不必使用%s然后格式化字符串。@user3234209很好,只是比str.split稍微慢一点目前还不清楚这种模式应该如何表现。为什么第二个示例从输出中删除
Some
?为什么要取消周期?其他类型的主角也应该被删除吗?仅仅
split
ting字符串会产生您可以使用的输出吗?@user2357112我会编辑it@user2357112我忘了回答关于前导字符和拆分的第二个问题,但我认为正则表达式比尝试拆分字符串更好。至于前导字符,如果我理解正确,任何字符都应该工作,无论它是数字、字母、十进制还是其他任何字符。
In [228]: parts = s.split(' ', 1)

In [229]: command, extra = parts[0], "" if len(parts)==1 else parts[1]