如何解析name = value ^^ name = value ^^ name = value

时间:2012-10-19 22:42:42

标签: java regex string parsing

我的问题:这是非常具体的。我正在考虑解析以下文本的最简单方法:

^^domain=domain_value^^version=version_value^^account_type=account_type_value^^username=username_value^^password=password_value^^type=type_value^^location=location_value^^id=xxx^^cuid=cuid_value^^

每次都会出现这样的情况。一些要求:

  • 并非每次都会出现所有这些键值对。
  • 他们的顺序可能不同

我正在寻找类似这样的代码:

private String[] getKeyValueInfo(String allStuff) {
  String domain = someAwesomeMethod("domain", allStuff);
  String version = someAwesomeMethod("version", allStuff);
  String account_type = someAwesomeMethod("account_type", allStuff);
  String username = someAwesomeMethod("username", allStuff);
  String password = someAwesomeMethod("password", allStuff);
  String type = someAwesomeMethod("password", allStuff);
  String location = someAwesomeMethod("location", allStuff);
  String id = someAwesomeMethod("id", allStuff);
  String cuid  = someAwesomeMethod("cuid", allStuff);
  return new String[] {domain, version, account_type, username, password, type, location, id, cuid};
}

我不知道的是someAwesomeMethod(String key, String allStuff)应包含的内容。

我在想什么:这样的事情:

private String someAwesomeMethod(String key, String allStuff) {
  Pattern patt = Pattern.compile("(?i)^^" + key + "=(.*?)^^", Pattern.DOTALL);
  Matcher matcher = patt.matcher(allStuff);
  if (matcher.find()) {
    return matcher.group(1);
  }
  return null;
}

这有什么问题:

如果我不得不这么做,我担心这会有点慢/笨重。所以我正在寻找任何提示/建议。

2 个答案:

答案 0 :(得分:5)

如果你必须做很多事情,我会制作一张地图,就像

一样
Map<String, String> m = new HashMap<String, String>();
for (String s : stuff.split("\\^\\^"))  // caret needs escaping
{  
    String[] kv = s.split("=");
    m.put(kv[0]) = kv[1];
}

然后查找您刚刚执行的密钥m.get("key")

答案 1 :(得分:0)

String.split()适用于

strVar = /* Your big long string */
String[] vars = strVar.split("\\^\\^"); // needs escaping