How to parse a command line with regular expressions?

后端 未结 13 701
离开以前
离开以前 2020-12-03 16:02

I want to split a command line like string in single string parameters. How look the regular expression for it. The problem are that the parameters can be quoted. For exampl

13条回答
  •  萌比男神i
    2020-12-03 16:20

    You should not use regular expressions for this. Write a parser instead, or use one provided by your language.

    I don't see why I get downvoted for this. This is how it could be done in Python:

    >>> import shlex
    >>> shlex.split('"param 1" param2 "param 3"')
    ['param 1', 'param2', 'param 3']
    >>> shlex.split('"param 1" param2 "param 3')
    Traceback (most recent call last):
        [...]
    ValueError: No closing quotation
    >>> shlex.split('"param 1" param2 "param 3\\""')
    ['param 1', 'param2', 'param 3"']
    

    Now tell me that wrecking your brain about how a regex will solve this problem is ever worth the hassle.

提交回复
热议问题