Search code examples
javastring-parsing

How to parse string to map in java


How to write parser for below string in java

"SiteId:BLR232#Latitude:12.918444#Longitude:77.5940136#NetworkType:4g#Type:NONE#Type of Complaint:Call Drop#Sample Number:7022979575#Problem Description:agshjs vshsijsb#"

so that result output will be in hashmap java

Key = SiteId, Value = BLR232
Key = Type, Value = NONE
Key = Problem Description, Value = agshjs vshsijsb
Key = Sample Number, Value = 7022979575
Key = NetworkType, Value = 4g
Key = Latitude, Value = 12.918444
Key = Type of Complaint, Value = Call Drop
Key = Longitude, Value = 77.5940136

I had tried using Pattern p = Pattern.compile("(\\w+):(\\w+)"); but not working exactly what i need.


Solution

  • Your (\w+):(\w+) only matches single words before : and after it. You have # as a record delimiter and : as a key-value delimiter, so you cannot rely on just \w class.

    Note that you can solve the problem with just splitting the string with # into key-value pairs and then split each key-value pair with ::

    String str = "SiteId:BLR232#Latitude:12.918444#Longitude:77.5940136#NetworkType:4g#Type:NONE#Type of Complaint:Call Drop#Sample Number:7022979575#Problem Description:agshjs vshsijsb#";
    String[] kvps = str.split("#");
    Map<String, String> res = new HashMap<String, String>();
    for(String kvp : kvps) {
        String[] parts = kvp.split(":");
        res.put(parts[0], parts[1]);
        System.out.println(parts[0] + " - " + parts[1]); // just demo
    }
    

    See IDEONE demo

    If you need a regex by all means, you can use the following pattern with Matcher#find():

    ([^#:]+):([^#]+)
    

    Explanation:

    • ([^#:]+) - 1+ characters other than # and : (thus, we stay inside the key-value pair and match the key)
    • : - a literal colon
    • ([^#]+) - 1+ characters other than # (thus, we match the value up to the #.

    See regex demo