繁体   English   中英

为最后一次出现的字符拆分字符串

[英]Splitting a string for last occurrence a character

我正在尝试使用如下格式拆分字符串:

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

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

例如

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

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

关于如何做的任何想法?

我尝试使用正则表达式和 Stringtokenizer,但我无法恢复最后一次出现的“,”

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

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

(见Regex101

这匹配 a ,它没有后续的,直到下一个=

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

完整代码

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());  
     });

    }    
}

Output :

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

Output:

abc=cde

dfe=lk,f

sss=f,d,s

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM