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:

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 Do you mean like this? (?: : |\G(?!^)(?:\s*,\s*)?)(\w+\s*=\s*(?:\[\w+\]|\w+)) regex101.com/r/kSFJ91/1 Or exclude the / and | in a lookbehind (?<![/|])\b\w+\s*=\s*(?:\[\w+\]|\w+)(?=\s*[,/]|$) regex101.com/r/DBtyio/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.