我的问题:非常具体。我正在尝试考虑解析以下文本的最简单方法:
^^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;
}
那有什么问题:
我担心如果我不得不经常这样做会有点慢/麻烦。所以我正在寻找任何提示/建议。