协助正则表达式python

时间:2014-03-10 02:05:01

标签: python regex python-3.x

我需要一个正则表达式模式的帮助,允许我在下面做,但我不太清楚如何。

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"

正在使用正则表达式

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()

1 个答案:

答案 0 :(得分:1)

这样的东西?

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 maxsplit 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']

为了避免解包错误(如果你坚持打开包装):

In [228]: parts = s.split(' ', 1)

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