javascript - Wondering if it would be possible using regex -
consider following example
<pre> { "cccccc": {}, "aaaaaa": { "xxxxxxxx": true }, "bbbbbbb": { "yyyyy": true, "zzzzzzzz": true } } </pre>
i can select x y , z , assign action function them
re = /"(.*?)(": (true|false))/g hl = '"<span style="color:blue;" onclick="action(\'aaaaaa\',\'$1\')">$1</span>$2'; s = s.replace(re, hl)
but failed figure out how regex aaaaaa
or bbbbbbb
depending on position first action argument fixed aaaaaa
, should bbbbbbb
y or z
you in 2 step regex if desire:
[^"]*"((?:[^\\"]|\\.)*)"\s*:\s*{(.*)}
your odd matches keys, , matches values. you'd need run secondary regex on matches find values, like:
[^"]*"((?:[^\\"]|\\.)*)"\s*:\s*(?:true|false)
which should extract values.
edit:
you cannot accomplish single regex , here's why, if capture each variable in quotes you'll end 6 captures:
- cccccc
- aaaaaa
- xxxxxxxx
- bbbbbbb
- yyyyy
- zzzzzzzz
it's unclear of these without visual inspection of input. way define variable contained variable extract variable name contents therein meter gives defines capture is. first capture give you:
- cccccc
- aaaaaa
- "xxxxxxxx": true
- bbbbbbb
- "yyyyy": true, "zzzzzzzz": true
javastript not support repetitive captures. if did think complexity of combining 2 regexes one:
[^"]*"((?:[^\\"]|\\.)*)"\s*:\s*{((?:[^"]*"((?:[^\\"]|\\.)*)"\s*:\s*{(.*)})*)}
you'd end following matches:
- cccccc
- aaaaaa
- "xxxxxxxx": true
- xxxxxxxx
- bbbbbbb
- "yyyyy": true, "zzzzzzzz": true
- yyyyy
- zzzzzzzz
you'd have process whole set of captures, identifying captures contents. finding empty capture or capture containing '"'
character. assume every variable preceding capture of contents containing variable, , every variable succeeding capture of contents contained variable; next containing variable.
of course aside creating lot of work, linked, isn't possible in javascript regexes. i'll return original answer's statement: bergi mentioned avoidance of regexes in favor of programatic solution, json.parse
or similar, should preferred because of fragility of regexes.
Comments
Post a Comment