Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parsing string

I'm looking to parse the following string in java

<some lines here>
Key1:thingIWantToKnow
Key2:otherThing
Key3:bla
Key4:bla
Key5:bla
<(possibly) more lines here>

All lines end with a newline (\n) character. I'm looking to store the value pair once I find the key's I'm care about.

like image 702
erics Avatar asked Jun 02 '26 18:06

erics


2 Answers

If a Map is what you want:

Map<String, String> keyValueMap = new HashMap<String,String>();

String[] lines = input.split("\n");
if (lines == null) {
  //Compensate for strange JDK semantics
  lines = new String[] { input };
}

for (String line : lines) {
  if (!line.contains(":")) {
    //Skip lines that don't contain key-value pairs
    continue;
  }
  String[] parts = line.split(":");
  keyValueMap.put(parts[0], parts[1]);
}

return keyValueMap;
like image 89
Axel Fontaine Avatar answered Jun 04 '26 06:06

Axel Fontaine


  1. If the data is in a String then you can use a StringReader to read one line of text at a time.
  2. For each line you read you can use String.startsWith(...) to see if you found one of your key lines.
  3. When you find a line containing key/value data then you can use String.split(...) to get the key/value data separately.
like image 37
camickr Avatar answered Jun 04 '26 07:06

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!