regex - Javascript string.match refuses to return an array of more than one match -
i have string expect formatted so:
{list:[names:a,b,c][ages:1,2,3]}
my query looks in javascript:
var str = "{list:[names:a,b,c][ages:1,2,3]}"; var result = str.match(/^\{list:\[names:([a-za-z,]*)\]\[ages:([0-9,]*)\]\}$/g);
note: recognize regex pass "ages:,,,", i'm not worried @ moment.
i expecting back:
result[0] = "{list:[names:a,b,c][ages:1,2,3]}" result[1] = "a,b,c" result[2] = "1,2,3"
but no matter seem regular expression, refuses return array of more 1 match, full string (because passes, start):
result = ["{list:[names:a,b,c][ages:1,2,3]}"]
i've looked through bunch of questions on here already, other 'intro' articles, , none of them seem address basic. i'm sure it's foolish i've overlooked, have no idea :(
so difference in how global flag applied in regular expressions in javascript.
in .match
, global flag (/g
@ end) return array of every incident regular expression matches string. without flag, .match
return array of of groupings in string.
eg:
var str = "{list:[names:a,b,c][ages:1,2,3]}"; str += str; // removed ^ , $ demonstration purposes var results = str.match(/\{list:\[names:([a-za-z,]*)\]\[ages:([0-9,]*)\]\}/g) console.log(results) // ["{list:[names:a,b,c][ages:1,2,3]}", "{list:[names:a,b,c][ages:1,2,3]}"] str = "{list:[names:a,b,c][ages:1,2,3]}{list:[names:a,b,c][ages:3,4,5]}"; results = str.match(/\{list:\[names:([a-za-z,]*)\]\[ages:([0-9,]*)\]\}/g); console.log(results) //["{list:[names:a,b,c][ages:1,2,3]}", "{list:[names:a,b,c][ages:3,4,5]}"]
now, if remove /g
flag:
// leaving str above results = str.match(/\{list:\[names:([a-za-z,]*)\]\[ages:([0-9,]*)\]\}/); console.log(results) //["{list:[names:a,b,c][ages:1,2,3]}", "a,b,c", "1,2,3"]
and note why regex.exec
worked, that because:
if regular expression not include g flag, returns same result regexp.exec(string).
Comments
Post a Comment