javascript - Regular expression that matches group as many times as it can find -


i have written regular expression match tags this:

@("hello, world" bold italic font-size="15") 

i want regular expression match these strings: ['hello, world', 'bold', 'italic', 'font-size="15"'].

however, these strings matched: ['hello, world', 'font-size="15"'].

other examples:

  1. (success)@("test") -> ["test"]
  2. (success)@("test" bold) -> ["test", "bold"]
  3. (fail)@("test" bold size="15") -> ["test", "bold", 'size="15"']

i have tried using regular expression:

\@\(\s*"((?:[^"\\]|\\.)*)"(?:\s+([a-za-z0-9-_]+(?:\="(?:[^"\\]|\\.)*")?)*)\s*\) 

a broken down version:

\@\(   \s*   "((?:[^"\\]|\\.)*)"   (?:     \s+     (       [a-za-z0-9-_]+       (?:         \=         "(?:[^"\\]|\\.)*"       )?     )   )*   \s* \) 

the regular expression trying

  1. match beginning of sequence ($(),
  2. match string escaped characters,
  3. match (>= 1) blanks,
  4. (optional, grouped (5)) match = sign,
  5. (optional, grouped (4)) match string escaped characters,
  6. repeat (3) - (5)
  7. match end of sequence ())

however, regular expression matches "hello, world" , font-size="15". how can make match bold , italic, i.e. match group ([a-za-z0-9-_]+(?:\="(?:[^"\\]|\\.)*")?) multiple times?

expected result: ['"hello, world"', 'bold', 'italic', 'font-size="15']

p.s. using javascript native regular expression

you need 2-step solution:

example code:

var re = /@\((?:\s*(?:"[^"\\]*(?:\\.[^"\\]*)*"|[\w-]+(?:="?[^"\\]*(?:\\.[^"\\]*)*"?)?))+\s*\)/g;   var re2 = /(?:"([^"\\]*(?:\\.[^"\\]*)*)"|[\w-]+(?:="?[^"\\]*(?:\\.[^"\\]*)*"?)?)/g;  var str = 'text here @("hello, world" bold italic font-size="15") , here\ntext there @("welcome home" italic font-size="2345") , there';  var res = [];    while ((m = re.exec(str)) !== null) {      tmp = [];      while((n = re2.exec(m[0])) !== null) {        if (n[1]) {          tmp.push(n[1]);        } else {          tmp.push(n[0]);        }      }      res.push(tmp);  }  document.body.innerhtml = "<pre>" + json.stringify(res, 0, 4) + "</pre>";


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -