【问题标题】:Assistance with regex python协助正则表达式 python
【发布时间】: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


【解决方案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.splitmaxsplit1

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]

【讨论】:

  • 几乎,但是如果只有 ".SomeCommand" 怎么办?它给了我一个 NoneType 错误,但几乎可以正常工作。
  • @user3234209 如果你不知道这个命令是什么,你如何识别它?给我们您的规则;)该命令是否包含空格?还是用双引号括起来?
  • @user3234209 如果您的命令不包含空格,请查看我的更新
  • 我编辑了答案以显示有效的正则表达式。它只是您的修改版本,因此您不必使用 %s 然后格式化字符串。
  • @user3234209 嗯,不错,就是比str.split慢了一点;)
猜你喜欢
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 2021-09-01
  • 2019-02-10
  • 2018-11-05
相关资源
最近更新 更多