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:
- (success)
@("test") -> ["test"]
- (success)
@("test" bold) -> ["test", "bold"]
- (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
- match beginning of sequence (
$(
), - match string escaped characters,
- match (>= 1) blanks,
- (optional, grouped (5)) match
=
sign, - (optional, grouped (4)) match string escaped characters,
- repeat (3) - (5)
- 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:
- extracting substrings
@\((?:\s*(?:"[^"\\]*(?:\\.[^"\\]*)*"|[\w-]+(?:="?[^"\\]*(?:\\.[^"\\]*)*"?)?))+\s*\)
, - tokenizing match
(?:"([^"\\]*(?:\\.[^"\\]*)*)"|[\w-]+(?:="?[^"\\]*(?:\\.[^"\\]*)*"?)?)
.
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
Post a Comment