Can this be done with regex? -
i have string different length sub-strings split symbol '_' , sub-strings have split in multiple sub-sub-strings...
example:
"_foo-2_bar-12_un[3;1]iver[3]se[3-7]"
should split in groups this:
"foo-2", "2", "bar-12", "12", "un[3;1]", "3;1", "iv", "er[3]", "3", "se[3-7]", "3-7"
i've come this:
/(?:((?:(?:\[([a-z0-9;-]+)\])|(?<=_)(?:[a-z0-9]+)|-([0-9]+))+))/ig
the problem encounter last part. , after finicking around started think whether or not possible. it?
any kind of guidance appreciated.
you can use following regex:
/[^\w_]+(?:\[([^\][]*)]|-([^_]+))/g
see regex demo
the pattern matches 1+ char alphanumeric sequence ([^\w_]+
) followed either [...]
substrings having no [
, ]
inside (with \[([^\][]*)]
- note captures inside [...]
group 1) or hyphen followed 1+ characters other _
(and part after -
captured group 2).
var re = /[^\w_]+(?:\[([^\][]*)]|-([^_]+))/g; var str = '_foo-2_bar-12_un[3;1]iver[3]se[3-7]'; var res = []; while ((m = re.exec(str)) !== null) { res.push(m[0]); if (m[1]) { res.push(m[1]); } else { res.push(m[2]); } } document.body.innerhtml = "<pre>" + json.stringify(res, 0, 4) + "</pre>";
in code, match object analyzed @ each iteration: 0th group (the whole match) ias added final array, , if group 1 matched, group 1 added, else, group 2 added resulting array.
Comments
Post a Comment