Splitting the string in key=value groups using Regex (Java) -
i not big expert in regexp, that's why ask suggest efficient way of splitting string in key=value groups.
the input string:
x-x="11111" y-y="john-doe 23" db {rty='y453'} code {codedate='2000-03-01t00:00:00'}
what need key=value pairs:
key=x-x, value="11111" key=y-y, value="john-doe 23" key=rty, value='y453' key=codedate, value='2000-03-01t00:00:00'
my solution here fear it's not simplest one.
string str = "x-x=\"11111\" y-y=\"john-doe 23\" db {rty='y453'} code {codedate='2000-03-01t00:00:00'}"; matcher m = pattern.compile("(\\w+-*\\w*)=((\"|')(\\w+( |-|:)*)+(\"|'))").matcher(str); while(m.find()) { string key = m.group(1); string value = m.group(2); system.out.printf("key=%s, value=%s\n", key, value); }
thanks in advance help.
you can use regex 3 capturing groups , back-reference:
([\w-]+)=((['"]).*?\3)
regex breakup:
([\w-]+)
: match , capture key name in group #1=
: match=
(
: start group #2(['"])
: match , capture quote in group #3.*?
: match 0 or more of character (lazy match)\3
: back-reference group #3 match closing quote of same type
)
: end of capture group #2
you matches in .group(1)
, .group(2)
.
Comments
Post a Comment