本文介紹了將 key=value 的字符串解析為 Map的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在使用一個提供 XML 的 API,我需要從一個實際上是字符串的標簽中獲取地圖.示例:
I'm using an API that gives me a XML and I need to get a map from one tag which is actually a string. Example:
擁有
Billable=7200,Overtime=false,TransportCosts=20$
我需要
["Billable"="7200","Overtime=false","TransportCosts"="20$"]
問題是字符串是完全動態的,所以,它可以像
The problem is that the string is totally dynamic, so, it can be like
Overtime=true,TransportCosts=one, two, three
Overtime=true,TransportCosts=1= 1,two, three,Billable=7200
所以我不能只用逗號分隔,然后用等號分隔.是否可以使用正則表達式將類似的字符串轉換為地圖?
So I can not just split by comma and then by equal sign. Is it possible to convert a string like those to a map using a regex?
到目前為止我的代碼是:
My code so far is:
private Map<String, String> getAttributes(String attributes) {
final Map<String, String> attr = new HashMap<>();
if (attributes.contains(",")) {
final String[] pairs = attributes.split(",");
for (String s : pairs) {
if (s.contains("=")) {
final String pair = s;
final String[] keyValue = pair.split("=");
attr.put(keyValue[0], keyValue[1]);
}
}
return attr;
}
return attr;
}
提前致謝
推薦答案
你可以用
(w+)=(.*?)(?=,w+=|$)
請參閱 正則表達式演示.
詳情
(w+)
- 第 1 組:一個或多個單詞字符=
- 一個等號(.*?)
- 第 2 組:除換行符以外的任何零個或多個字符,盡可能少(?=,w+=|$)
- 需要,
,然后是 1+ 個單詞字符,然后是=的正向前瞻代碼>,或字符串的結尾緊挨當前位置的右側.
(w+)
- Group 1: one or more word chars=
- an equal sign(.*?)
- Group 2: any zero or more chars other than line break chars, as few as possible(?=,w+=|$)
- a positive lookahead that requires a,
, then 1+ word chars, and then=
, or end of string immediately to the right of the current location.
Java 代碼:
public static Map<String, String> getAttributes(String attributes) {
Map<String, String> attr = new HashMap<>();
Matcher m = Pattern.compile("(\w+)=(.*?)(?=,\w+=|$)").matcher(attributes);
while (m.find()) {
attr.put(m.group(1), m.group(2));
}
return attr;
}
Java 測試:
String s = "Overtime=true,TransportCosts=1= 1,two, three,Billable=7200";
Map<String,String> map = getAttributes(s);
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
結果:
Overtime=true
Billable=7200
TransportCosts=1= 1,two, three
這篇關于將 key=value 的字符串解析為 Map的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!