我需要帮助使用正则表达式将字符串中的这些参数提取/拆分为参数和值组。
Input -> collection_a=['U1', 'U2'], collection_b=['U1', 'U2']
output -> Group Parameter = collection_a
Group Value = ['U1', 'U2']
Group Parameter = collection_b
Group Value = ['U1', 'U2']
Input -> collection=['U1', 'U2'], callback_macro=utils.user_email(user_id=$$)
output -> Group Parameter = collection
Group Value = ['U1', 'U2']
Group Parameter = callback_macro
Group Value = utils.user_email(user_id=$$)
Input -> collection=['U1', 'U2'], callback_macro=utils.user_email(user_id=$$, config={'user': 'ADMIN'})
output -> Group Parameter = collection
Group Value = ['U1', 'U2']
Group Parameter = callback_macro
Group Value = utils.user_email(user_id=$$)
Input -> collection=['U1','U2'], callback_macro=string.replace(value=$$, pattern=^(.*)$, replacement={'user': $1})
output -> Group Parameter = collection
Group Value = ['U1', 'U2']
Group Parameter = callback_macro
Group Value = string.replace(value=$$, pattern=^(.*)$, replacement={'user': $1})
我正在使用这个正则表达式
/((\s*(?<parameter>[a-z_]+)\s*=\s*(?<value>((?!(,\s*[a-z_]+)\s*=\s*).)*)),{1,})/g
,它在情况 1 和情况 2 中完美运行,但在情况 3 和 4 中中断,因为在情况 3 和 4 中它包含 =
在参数值中。
正则表达式链接-https://regex101.com/r/U2CaLb/1
有这些要求做拆分会非常困难
您可以匹配key/value并将它们放入数组中。
请注意,第三个输入样本不遵循其他模式。
这里有一些选项可供选择。
方法 1 这个正则表达式使用单级大括号匹配作为它的一部分。
(\w+)=((?:\[.*?\]|\(.*?\)|{.*?}|[^,\r\n])*)
https://regex101.com/r/fnPb6e/1
( \w+ ) # (1)
=
( # (2 start)
(?:
\[ .*? \]
| \( .*? \)
| { .*? }
|
[^,\r\n]
)*
) # (2 end)
对于平衡大括号文本、PCRE 或非网络引擎:
方法2这个正则表达式是嵌套
()
,[]
,{}
(\w+)=((?:(\[(?:[^\[\]]++|(?3))*\])|(\((?:[^()]++|(?4))*\))|({(?:[^{}]++|(?5))*})|[^,\r\n])*)
https://regex101.com/r/dgWMDZ/1
( \w+ ) # (1)
=
( # (2 start)
(?:
( # (3 start)
\[
(?:
[^\[\]]++
| (?3)
)*
\]
) # (3 end)
| ( # (4 start)
\(
(?:
[^()]++
| (?4)
)*
\)
) # (4 end)
| ( # (5 start)
{
(?:
[^{}]++
| (?5)
)*
}
) # (5 end)
| [^,\r\n]
)*
) # (2 end)
方法3这个正则表达式将平衡嵌套在里面的不同括号
彼此(如果适用)。这将允许更多的内部支撑结构
项目,这种情况可能不需要,但将来可能需要。
这是增强的Method 2版本并包含该功能。
(\w+)=((?:(\[(?:[^\[\](){}]++|(?3))*\]|\((?:[^\[\](){}]++|(?3))*\)|{(?:[^\[\](){}]++|(?3))*})|[^,\r\n])*)
https://regex101.com/r/ZubSke/1
( \w+ ) # (1)
=
( # (2 start)
(?:
( # (3 start)
\[
(?:
[^\[\](){}]++
| (?3)
)*
\]
|
\(
(?:
[^\[\](){}]++
| (?3)
)*
\)
|
{
(?:
[^\[\](){}]++
| (?3)
)*
}
) # (3 end)
|
[^,\r\n]
)*
) # (2 end)
方法 4 与方法 3 相同,并添加了对简单单引号或双引号字符串的处理。
此正则表达式将混合在任何其他分隔符对中的引号解析
平衡,以及这些定界符之外。
请注意,有一个通过,垃圾收集器
[^,\r\n]
让捕获不平衡(\w+)=((?:(\[(?:[^\[\](){}'"]++|(?4)|(?3))*\]|\((?:[^\[\](){}'"]++|(?4)|(?3))*\)|{(?:[^\[\](){}'"]++|(?4)|(?3))*})|('[^'\r\n]*?'|"[^"\r\n]*?")|[^,\r\n])*)
https://regex101.com/r/090iI7/1
( \w+ ) # (1)
=
( # (2 start)
(?:
( # (3 start)
\[
(?:
[^\[\](){}'"]++
| (?4)
| (?3)
)*
\]
|
\(
(?:
[^\[\](){}'"]++
| (?4)
| (?3)
)*
\)
|
{
(?:
[^\[\](){}'"]++
| (?4)
| (?3)
)*
}
) # (3 end)
| ( # (4 start)
' [^'\r\n]*? '
|
" [^"\r\n]*? "
) # (4 end)
|
[^,\r\n]
)*
) # (2 end)