Question

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.

Was it helpful?

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 

OTHER TIPS

A basic solution based on regular expressions might look like this:

String input = "id:1234 alert:a-b up:12.3 down:12.3";
Matcher matcher = Pattern.compile("(\\S+):(\\S+)").matcher(input);

while (matcher.find()) {
  System.out.println(matcher.group(1) + " = " + matcher.group(2));
}

This assumes you are looking for one or more non-whitespace characters, then a colon, then one or more non-whitespace characters.

Output:

id = 1234
alert = a-b
up = 12.3
down = 12.3

You can use the method .split() from the String class.

Check this out:

String line = "id:1234 alert:a-b up:12.3 down:12.3";
String []splittedLine = line.split(" ");
for(int i = 0; i <= splittedLine.length;i++){
   System.out.println(splittedLine[i]);
}

What you are doing here is splitting your string line on every whitespace character it found. This is the result:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top