Search code examples
javastringxml-parsingsubstringstring-parsing

Best way to select parts certain parts of data in a string that changes in size


I'm looking for a good method of parsing certain parts of information in a string that changes in size.

For example, the string might be

"id:1234 alert:a-b up:12.3 down:12.3"

and I need to pick out the value for id, alert, up and down so my initial thought was substring but then I thought that length of the string can change in size for example

"id:123456 alert:a-b-c-d up:12.345 down:12.345"

So using substring each time to look at say characters 3 to 7 may not work each time because it would not capture all of the data needed.

What would be a smart way of selecting each value that is needed? Hopefully I've explained this well as I normally tend to confuse people with my bad explanations. I am programming in Java.


Solution

  • You could simply use String.split(), first to tokenize the whitespace and then to tokenize on your key/value separator (colon in this case):

    String line = "id:1234   alert:a-b   up:12.3 down:12.3";
    // first split the line by whitespace
    String[] keyValues = line.split("\\s+");
    
    for (String keyValueString : keyValues) {
        String[] keyValue = keyValueString.split(":");
        // TODO might want to check for bad data, that we have 2 values
        System.out.println(String.format("Key: %-10s Value: %-10s", keyValue[0], keyValue[1]));
    }
    

    Result:

    Key: id         Value: 1234      
    Key: alert      Value: a-b       
    Key: up         Value: 12.3      
    Key: down       Value: 12.3