【问题标题】:How to extract arguments using regex?如何使用正则表达式提取参数?
【发布时间】:2019-05-26 16:17:10
【问题描述】:

我想使用正则表达式提取参数(命令行参数的类型)。 在这里,我将字符串作为输入并将参数作为组获取

基本上我希望正则表达式中的集合既排除又包含一些字符。

import re

ppatt=r"( --(?P<param>([^( --)]*)))"
a=[x.group("param") for x in re.finditer(ppatt,"command --m=psrmcc;ld -  --kkk gtodf --klfj")]
print(a)

我希望输出是

['m=psrmcc;ld - ', 'kkk gtodf', 'klfj']

但输出是

['m=psrmcc;ld', 'kkk', 'klfj']

【问题讨论】:

  • 仅供参考,如果您的要求与普通命令行参数没有任何不同,您可以使用argparse
  • @ggorlen,谢谢回复。但在我的情况下,我还需要空格和特殊字符

标签: regex python-3.x regex-lookarounds regex-group regex-greedy


【解决方案1】:

我们也许可以使用带有单词边界的字符列表来解决这个问题,也许使用类似于以下的表达式:

(?:.+?)(\b[A-Za-z=;\s]+\b)

如果我们希望有更多的字符,我们会将其添加到:

[A-Za-z=;\s]

在这里,我们没有使用非捕获组来捕获不需要的字符:

(?:.+?)

然后我们收集包装在捕获组中的所需字符,我们可以使用 $1 简单地调用它:

(\b[A-Za-z=;\s]+\b)

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?:.+?)(\b[A-Za-z=;\s]+\b)"

test_str = "command --m=psrmcc;ld -  --kkk gtodf --klfj"

subst = "\\1\\n"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

正则表达式电路

jex.im 可视化正则表达式:

DEMO

【讨论】:

    【解决方案2】:

    您可以使用re.split

    例如:

    import re
    
    print(re.split(r"--", "command --m=psrmcc;ld -  --kkk gtodf --klfj")[1:])
    #or
    print("command --m=psrmcc;ld -  --kkk gtodf --klfj".split("--")[1:])
    

    输出:

    ['m=psrmcc;ld -  ', 'kkk gtodf ', 'klfj']
    

    【讨论】:

    • 甚至不需要re - string.split 也可以。
    • 是的,你是对的 :) print("command --m=psrmcc;ld - --kkk gtodf --klfj".split("--")[1:])
    猜你喜欢
    • 2015-10-21
    • 1970-01-01
    • 2018-11-28
    • 2021-11-27
    • 1970-01-01
    • 2011-06-15
    • 2021-12-16
    相关资源
    最近更新 更多