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:

  1. cccccc
  2. aaaaaa
  3. xxxxxxxx
  4. bbbbbbb
  5. yyyyy
  6. 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:

  1. cccccc

  2. aaaaaa
  3. "xxxxxxxx": true
  4. bbbbbbb
  5. "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:

  1. cccccc

  2. aaaaaa
  3. "xxxxxxxx": true
  4. xxxxxxxx
  5. bbbbbbb
  6. "yyyyy": true, "zzzzzzzz": true
  7. yyyyy
  8. 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

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -