my goal is to parse a string with an specific format to generate an javascript object structure out of it.
one idea was to use the String.replace with an function as parameter. so in the function you get all parts of the match. my test / example till now:
the string:
!Norm: DIN 7985;
M2: 2, 2, 2;
M3:3,3;
M10: 20,25;
!Norm: DIN 7985 TX;
M4: 4, 4 , 4;
my test code:
console.clear();
var sTmp = "!Norm: DIN 7985;\n M2: 2, 2, 2;\n M3:3,3;\n M10: 20,25;\n !Norm: DIN 7985 TX;\n M2: 6, 10 , 16;";
//console.log(sTmp);
function replacer(match, p1, p2, p3, p4, offset, string){
//console.log("-");
console.log("match:", match);
console.log("p1:", p1);
console.log("p2:", p2);
console.log("p3:", p3);
console.log("p4:", p4);
console.log("offset:", offset);
console.log("string:", string);
return "#";
}
//(?=!Norm:\s?(.+);\s+)
sTmp.replace(/\s*!Norm:\s?(.+);\s+(M\d+:.*\s*;)/g, replacer);
(tested in firebug) console log (shortend):
match: !Norm: DIN 7985; M2: 2, 2, 2;
p1: DIN 7985
p2: M2: 2, 2, 2;
p3: 0
p4: !Norm: DIN 7985; M2: 2, 2, 2; M3:3,3; M10: 20,25; ....
offset: undefined
string: undefined
match: !Norm: DIN 7985 TX; M4: 4, 4 , 4;
p1: DIN 7985 TX
p2: M4: 4, 4 , 4;
p3: 52
p4: !Norm: DIN 7985; M2: 2, 2, 2; M3:3,3; M10: 20,25; !Norm: DIN 7985 TX; M4: 4, 4 , 4;
....
so i can see that the idea works- it matches the norm and i get the Info in one substring.
now there are the M3:... parts.
so is there a option to specify that the part (M\d+:.*\s*;)
matches up to the next !Norm: instead of the ; at the first occurrence?
i think it should be possible with a lookahead or something?
the goal behind this idea is to generate an javascript object like this out of the string:
oDataTmp = {
DIN 7985 : {
M2 : ["2", "2", "2"],
M3 : ["3", "3"],
M10 : ["20", "25"],
}
DIN 7985 TX : {
M4 : ["4", "4", "4"],
}
}
i know you can do this by split and then parse line by line. i love the challenge to get this brain thing done and to understand how to do it :-)