1

I am working on a C# regex to achieve the following result.

command value1 valu2 : param1=value1, param2=[valu2], param3 = vaule3 /option1 |option2

Group1: param1=value1
Group2: param2=[valu2]
Group3: param3 = vaule3

My current regex:

(\w+\s*\=\s*\w+)(,\w+\s*\=\s*[a-zA-Z0-9\]\[]+)*

I am missing to include the following:

  1. Should start with :
  2. Should allow [] char into the value section
  3. Should stop at / or | or end of line

Here is test test: https://regex101.com/r/5kPXAz/1

I have used examples from:

Salim
  • 495
  • 3
  • 20

1 Answers1

1

The pattern that you tried does not match all values because matching the square brackets using the character class will only happen in the second part of the pattern after matching a comma first.

You could use an alternation to match either word chars surrounded by square brackets or only word chars and make use of a positive lookahead to assert either a / or , or the end of the line.

\w+\s*=\s*(?:\[\w+\]|\w+)(?=\s*[,/]|$)

Explanation

  • \w+\s*=\s*Match 1+ word chars and an equals sign between optional whitespace chars
  • (?: Non capture group
    • \[\w+\] Match [ 1+ word chars and ]
    • | Or
    • \w+ Match 1+ word chars
  • ) Close group
  • (?=\s*[,/]|$) Positive lookahead, assert what is on the right is either , or / or end of line

.NET regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Hello, Thanks for your answer. A few point: It does not match the starting : should I better do that in an initial step? It also does not stop at / |. Try to match: command value1 valu2 : param1=value1, param2=[valu2], param3 = vaule3 /option1 /option2 |ShouldNotMatchParam=FaultyValue2 – Salim May 24 '20 at 08:14
  • 1
    @Salim Do you mean like this? `(?: : |\G(?!^)(?:\s*,\s*)?)(\w+\s*=\s*(?:\[\w+\]|\w+))` https://regex101.com/r/kSFJ91/1 Or exclude the `/` and `|` in a lookbehind `(?<![/|])\b\w+\s*=\s*(?:\[\w+\]|\w+)(?=\s*[,/]|$)` https://regex101.com/r/DBtyio/1 – The fourth bird May 24 '20 at 08:20