0

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

^^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;
}

那有什么问题:

我担心如果我不得不经常这样做会有点慢/麻烦。所以我正在寻找任何提示/建议。

4

2 回答 2

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")

于 2012-10-19T22:47:20.250 回答
0

String.split() 将为此工作

strVar = /* Your big long string */
String[] vars = strVar.split("\\^\\^"); // needs escaping
于 2012-10-19T22:47:06.100 回答