Search code examples
javastringtext-extraction

How can i extract more couples of "Key = val_1,...,val_n" in a String?


I need to solve a problem. I have a String of "rules" that has not always the same order, and i should extract the Key and the value/s of each key. My Key/Value separator is the char "=", while the different couples separator is the char ";".
This string is composed of "Key_1 = Value_1, ... , Value_n; Key_2 = Value_1, ... , Value_n;".

Examples of my string is:

1) "Role = Student, Professor; HourFrom = 10:30; HourTo = 13:30;"
2) "HourFrom = 10:00; HourTo = 20:00;"
3) "Role = Professor; DayOfTheWeek = Monday, Friday;"
4) "DateFrom = 20/07/2020; DateTo = 19/08/2020;"

The possibilities are so many and the possible keys of my String are: Role, HourFrom, HourTo, DateFrom, DateTo, DayOfTheWeek. I guess I have something like 2^n combination, with n keys.

I'm really getting crazy, cause i don't have a string order so i don't know how to solve this problem. Hope you guys can help me, so thank you in advance.


Solution

  • You can use split by ";" and ":" after put values in a Map like this :

        String input1 = "Role = Student, Professor; HourFrom = 10:30; HourTo = 13:30;";
    
        String[] input = input1.split(";");
        Map<String,String> output = new HashMap<>();
        for (String s:input ){
            String[] value = s.split("=");
            if(value.length == 2) {
                output.put(value[0],value[1]);
            }else if (value.length == 1){
                output.put(value[0],null);
            }
        }
        output.entrySet().forEach(entry->{
            System.out.println("{"+entry.getKey() + " = " + entry.getValue()+"}");
        });
    

    result :

    { HourFrom = 10:30} { HourTo = 13:30} {Role = Student, Professor}