How to parse a command line with regular expressions?

后端 未结 13 725
离开以前
离开以前 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条回答
  •  清歌不尽
    2020-12-03 16:36

    Regex: /[\/-]?((\w+)(?:[=:]("[^"]+"|[^\s"]+))?)(?:\s+|$)/g

    Sample: /P1="Long value" /P2=3 /P3=short PwithoutSwitch1=any PwithoutSwitch2

    Such regex can parses the parameters list that built by rules:

    • Parameters are separates by spaces (one or more).
    • Parameter can contains switch symbol (/ or -).
    • Parameter consists from name and value that divided by symbol = or :.
    • Name can be set of alphanumerics and underscores.
    • Value can absent.
    • If value exists it can be the set of any symbols, but if it has the space then value should be quoted.

    This regex has three groups:

    • the first group contains whole parameters without switch symbol,
    • the second group contains name only,
    • the third group contains value (if it exists) only.

    For sample above:

    1. Whole match: /P1="Long value"
      • Group#1: P1="Long value",
      • Group#2: P1,
      • Group#3: "Long value".
    2. Whole match: /P2=3
      • Group#1: P2=3,
      • Group#2: P2,
      • Group#3: 3.
    3. Whole match: /P3=short
      • Group#1: P3=short,
      • Group#2: P3,
      • Group#3: short.
    4. Whole match: PwithoutSwitch1=any
      • Group#1: PwithoutSwitch1=any,
      • Group#2: PwithoutSwitch1,
      • Group#3: any.
    5. Whole match: PwithoutSwitch2
      • Group#1: PwithoutSwitch2,
      • Group#2: PwithoutSwitch2,
      • Group#3: absent.

提交回复
热议问题