我有一个字符串"values.component_category:monstor_client,dimensions.pool:rpool1,dimensions.env:prod,values.error_description:No content to map due to end-of-input↵ at [Source: java.io.StringReader@2ef452e5; line: 1, column: 1],values.incident_category:health"
并且只有在,
或values
后跟dimensions
时才尝试将其拆分。由于,
中有另一个; line: 1, column: 1
,我想逃避它。
我尝试使用正则表达式.split(/,?(values|dimensions)./)
预期产出:
[
"values.component_category:monstor_client",
"dimensions.pool:rpool1",
"dimensions.env:pord",
"values.error_description:No content to map due to end-of java.io.StringReader@2ef452e5; line: 1, column: 1]",
"values.incident_category:health"
]
答案 0 :(得分:2)
https://www.regular-expressions.info/lookaround.html
特别需要使用前瞻,例如:,(?=values|dimensions)
答案 1 :(得分:0)
您可以使用Array.reduce
和String.split()
来实现此目标:
var str = "values.component_category:monstor_client,dimensions.pool:rpool1,dimensions.env:prod,values.error_description:No content to map due to end-of-input↵ at [Source: java.io.StringReader@2ef452e5; line: 1, column: 1],values.incident_category:health";
var arr = str.split(/,(?=values|dimensions)/);
var result = arr.reduce((a,val)=>{
var key = val.substring(0, val.indexOf(":"));
var value = val.substring(val.indexOf(":")+1)
a[key] = value;
return a;
},{});
console.log(result);