Java parsing string

情到浓时终转凉″ 提交于 2019-12-22 10:55:57

问题


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.


回答1:


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;



回答2:


  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.



回答3:


You can use StringUtils.split

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html

If you're looking for lines that contain 'Key' after that, use StringUtils.contains

Not the fastest, but certainly the most convenient, and null-safe too.



来源:https://stackoverflow.com/questions/4822552/java-parsing-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!