Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript Regex - parse structured string to object with replace
    primarykey
    data
    text
    <p>my goal is to parse a string with an specific format to generate an javascript object structure out of it.</p> <p>one idea was to use the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter" rel="nofollow">String.replace</a> with an function as parameter. so in the function you get all parts of the match. my test / example till now:</p> <p>the string:</p> <pre><code> !Norm: DIN 7985; M2: 2, 2, 2; M3:3,3; M10: 20,25; !Norm: DIN 7985 TX; M4: 4, 4 , 4; </code></pre> <p>my test code:</p> <pre><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); </code></pre> <p>(tested in firebug) console log (shortend):</p> <pre><code>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; .... </code></pre> <p>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 <code>(M\d+:.*\s*;)</code> matches up to the next !Norm: instead of the ; at the first occurrence? i think it should be possible with a lookahead or something?</p> <p>the goal behind this idea is to generate an javascript object like this out of the string:</p> <pre><code> oDataTmp = { DIN 7985 : { M2 : ["2", "2", "2"], M3 : ["3", "3"], M10 : ["20", "25"], } DIN 7985 TX : { M4 : ["4", "4", "4"], } } </code></pre> <p>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 :-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload