简体   繁体   English

正则表达式匹配命令行中以逗号分隔的多个参数

[英]Regex match multiple parameters separated by comma in command line

I am working on a C# regex to achieve the following result.我正在研究 C# 正则表达式以实现以下结果。

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这是测试测试: https://regex101.com/r/5kPXAz/1

I have used examples from:我使用了以下示例:

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.您尝试的模式与所有值都不匹配,因为使用字符 class 匹配方括号只会在首先匹配逗号后出现在模式的第二部分。

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 \w+\s*=\s*匹配 1+ 个单词字符和可选空白字符之间的等号
  • (?: Non capture group (?:非捕获组
    • \[\w+\] Match [ 1+ word chars and ] \[\w+\]匹配[ 1+ 单词字符和]
    • | Or或者
    • \w+ Match 1+ word chars \w+匹配 1+ 个单词字符
  • ) Close group )关闭组
  • (?=\s*[,/]|$) Positive lookahead, assert what is on the right is either , or / or end of line (?=\s*[,/]|$)正向前瞻,断言右边是,/或行尾

.NET regex demo .NET 正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM