拆分字符串以最后一次出现一个字符



我正在尝试用这样的格式拆分字符串:

"abc=cde,dfe=lk,f,sss=f,d,s" 

我想通过使用第一组字符作为键,第二组字符作为值来恢复映射中的这些值。

例如

  • 键:abc,值:cde
  • 键:dfe,值:lk,f
  • 键:sss,值:f,d,s

因此,将这些值拆分为最后一次出现的","。

关于如何做到这一点的任何想法?

我尝试使用正则表达式和字符串标记器,但我无法恢复最后一次出现的",">

您可以使用以下正则表达式(可以优化):

,(?=(?:(?!,).)*=)

(见正则表达式101)

这匹配了在下一个=之前没有后续,,

为此,您需要使用正则表达式。

完整代码

public class Test {

public static void main(String args[]) {

String input = "abc=cde,dfe=lk,f,sss=f,d,s";
String[] arrOfStr = input.split(",(?=(?:(?!,).)*=)");

HashMap<String, String> properties = new HashMap<String, String>();

for(int i=0;i<arrOfStr.length;i++) {
String[] temp = arrOfStr[i].split("=");
properties.put(temp[0], temp[1]);           

}           
System.out.println("Input String     : " +input);
System.out.println("nFinal properties : ");

properties.entrySet().forEach(entry->{
System.out.println("key = " +entry.getKey() + " :: value = " + entry.getValue());  
});
}    
}

输出

Input String     : abc=cde,dfe=lk,f,sss=f,d,s
Final properties : 
key = dfe :: value = lk,f
key = sss :: value = f,d,s
key = abc :: value = cde

完整代码 :

public class Test {

public static void main(String args[]) {
String text = "abc=cde,dfe=lk,f,sss=f,d,s";
String[] parts = text.split(",");
Map<String, String> map = new LinkedHashMap<>();
String key = null;
StringBuilder value = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (parts[i].contains("=")) {
if (key != null) {
map.put(key, value.toString());
value.setLength(0);
}
String[] innerParts = parts[i].split("=");
key = innerParts[0];
value.append(innerParts[1]);
} else {
value.append(',').append(parts[i]);
}
}
map.put(key, value.toString());
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}   
}    
}

输出:

ABC=CDE

dfe=lk,f

SSS=f,d,s

最新更新