I have a string that looks like this: "[111-11] text here with digits 111, [222-22-22]; 333-33 text here" and I am trying to parse it so that I can extract the code [111-11], [222-22-22], [333-33] along with their respective text descriptions. The challenge is that the splitting pattern for the codes is not fixed except for the format xxx-xx or xxx-xx-xx.
I attempted to solve this issue using a specific method but encountered difficulties in extracting the digits from the description part. Using \D captures anything that is not a digit.
let text = "[111-11] text here with digits 111, [222-22-22]; 333-33 text here";
let codes=[];
let result = text.replace(/(\d{3}(-\d{2})+)(\D*)/g,(str, code, c, desc) => {
desc = desc.trim().replace(/[\[\]']+/g,'');
if (code) codes.push({'code':code.trim(),'desc': desc});
return str;
}); //parse and split codes
My desired outcome is structured as follows:
[{code:'111-11', desc:'text here with digits 111'},
{code:'222-22-22', desc:''},
{code:'333-33', desc:'text here'}]
Your assistance in solving this problem would be greatly appreciated.