Sai Ram Gupta
Sai Ram Gupta

Reputation: 1181

split by delimiter only if it is followed by some string

I have a string "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"

and trying to split it by , only if it is followed by string values or dimensions. Since there is another , in ; line: 1, column: 1 and I want to escape that.

I tried with regex .split(/,?(values|dimensions)./)

Expected output:

[
   "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"
]

Upvotes: 0

Views: 78

Answers (2)

Rafał Wrzeszcz
Rafał Wrzeszcz

Reputation: 2067

https://www.regular-expressions.info/lookaround.html

In particular you need to use look-ahead, something like: ,(?=values|dimensions)

Upvotes: 2

amrender singh
amrender singh

Reputation: 8239

You can use Array.reduce and String.split() to achieve this:

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);

Upvotes: 0

Related Questions