如何解析name = value ^^ name = value ^^ name = value [英] How to parse name=value^^name=value^^name=value
问题描述
我的问题:非常具体.我正在尝试解析以下文本的最简单方法:
My Question: It's very specific. I'm trying to think of the easiest way to parse the following text:
^^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^^
每次都会看起来完全一样.一些要求:
It will appear exactly like that every time. A few requirements:
- 并非所有这些键值对都会每次出现.
- 它们的顺序可能不同
我正在寻找类似这样的代码:
I'm looking for code something like this:
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)
应该包含什么.
What I don't know is what someAwesomeMethod(String key, String allStuff)
should contain.
我在想什么:
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;
}
这是怎么回事:
我担心如果我不得不经常这样做会有点慢/麻烦.因此,我正在寻找任何提示/建议.
I'm worried it'd be a little slow/cumbersome if I had to do this a lot. So I'm looking for any tips/suggestions.
推荐答案
如果必须要做很多,我会做一张地图,类似
If you have to do it a lot, i'd make a map, something along the lines of
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")
then to lookup a key you'd just do m.get("key")
这篇关于如何解析name = value ^^ name = value ^^ name = value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!