How to parse a command line with regular expressions?

后端 未结 13 704
离开以前
离开以前 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条回答
  •  Happy的楠姐
    2020-12-03 16:35

    If you are looking to parse the command and the parameters I use the following (with ^$ matching at line breaks aka multiline):

    (?^"[^"]*"|\S*) *(?.*)?
    

    In case you want to use it in your C# code, here it is properly escaped:

    try {
        Regex RegexObj = new Regex("(?^\\\"[^\\\"]*\\\"|\\S*) *(?.*)?");
    
    } catch (ArgumentException ex) {
        // Syntax error in the regular expression
    }
    

    It will parse the following and know what is the command versus the parameters:

    "c:\program files\myapp\app.exe" p1 p2 "p3 with space"
    app.exe p1 p2 "p3 with space"
    app.exe
    

提交回复
热议问题