使用正则表达式解析非常简单的JSON文件 [英] Using regex to parse a very simple JSON file
问题描述
我不确定是否可以完成,但是我想将一个非常简单的JSON文件解析为字符串数组.
I'm not sure if it can be done, but I'd like to parse a very simple JSON file to an array of Strings.
示例文件:
["String1", "String2", "oneMoreString"]
到目前为止,我还以为我会使用带有模式的Scanner来获取输出,但未能做到这一点.
So far I thought I'd use Scanner with a pattern to get my output, but failed to do this.
ArrayList<String> strings = new ArrayList<String>();
File f = new File("src/sample.txt");
String pattern = "\\s*[\"\"]\\s*";
try {
InputStream is = new FileInputStream(f);
Scanner s = new Scanner(is);
s.useDelimiter(pattern);
while (s.hasNext()){
strings.add(s.next());
}
s.close();
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
因为该模式显然是错误的,因为它会适当地考虑,",但是我希望它不会包含在内...:S
because the pattern is clearly wrong, since it considers ", " as it fits, but I'd like it wouldn't be included... :S
我也接受一些建议,这些建议可能会以任何其他可以解析的方式起作用.也许是JSON解析器?但是由于该文件是如此简单,所以我认为没有必要.
I also accept suggestions that may work to any other way this can be parsed. Maybe a JSON parser? but because the file is so simple I didn't consider it necessary.
推荐答案
最好使用Jackson映射器之类的JSON解析器来解析JSON字符串.
It is better to use a JSON parser like Jackson Mapper to parse a JSON String.
但是,如果您有一个简单的String,则可以快速使用示例正则表达式.
But to if you have a simple String you can use a sample Regular expression to it quickly.
尝试一下:
String str = "[\"String1\", \"String2\", \"oneMoreString\"]";
Pattern pattern = Pattern.compile("\"(.+?)\"");
Matcher matcher = pattern.matcher(str);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
// System.out.println(matcher.group(1));.
list.add(matcher.group(1));
}
这篇关于使用正则表达式解析非常简单的JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!