java - How to retrieve a value from a list of keys/values separated by pipes? -
i have string like:
string s = "a=xxx|b = yyy|c= zzz" i trying write function returns value corresponding given key not work expected (it returns empty string):
static string getvaluefromkey(string s, string key) { return s.replaceall(key + "\\s*=\\s*(.*?)(\\|)?.*", "$1"); } test:
static void test() { string s = "a=xxx|b = yyy|c= zzz"; assertequals(getvaluefromkey(s, "a"), "xxx"); assertequals(getvaluefromkey(s, "b"), "yyy"); assertequals(getvaluefromkey(s, "c"), "zzz"); } what regex need pass tests?
using replaceall here seems overkill, because method have iterate on entire string. instead use matcher , find method stop after matching searched regex (in out case key=value pair).
so maybe use like:
static string getvaluefromkey(string s, string key) { matcher m = pattern.compile( "(?<=^|\\|)\\s*" + pattern.quote(key) + "\\b\\s*=\\s*(?<value>[^|]*)") .matcher(s); if (m.find()) return m.group("value"); else return null;// or maybe return empty string "" may misleading // values empty strings }
Comments
Post a Comment