完全在这里工作:
{"air_date":"(.*)-.*-.*","episodes|(?:episode_|\G)number":(.*?),
Java 返回:java.lang.NumberFormatException: null
在线episodios.add(...)
[...]
Matcher filter = Pattern.compile("\\{\"air_date\":\"(.*)-.*-.*\",\"episodes|(?:episode_|\\G)number\":(.*?),").matcher(response);
while (filter.find()) {
episodios.add(new Episodio(idSerie, temporada, Integer.parseInt(filter.group(2))));
}
}
响应为:http://pastebin.com/m4EJ1iP5
我知道它是 JSON,而正则表达式不是最佳的。但这是必需的(老师)!
最佳答案
正如您在 debuggex 中看到的那样您的正则表达式的第一个匹配是
{"air_date":"2009-03-08","episodes
因此,您仅在第 1 组(2009
-03-08 部分)中匹配,但第 2 组为空(表示 null
),并且由于您将 null
传递给 Integer.parseInt
,因此您将收到 NumberFormatException: null
。确保您正在处理剧集匹配
episode_number":1,
测试组 2 的值是否不为 null
,如
while (filter.find()) {
if (filter.group(1) != null) {
this.ano = Integer.parseInt(filter.group(1));
}
if (filter.group(2) != null) {
episodios.add(new Episodio(idSerie, temporada, Integer.parseInt(filter.group(2))));
}
}
<小时/>
但在现实世界中,您不应该使用正则表达式来解析 JSon,而应该使用适当的解析器,例如 GSon、Jackson。以下是如何使用 GSon 实现此目的的示例。
String data = new Scanner(new File("input.txt")).useDelimiter("\\A").next();
Gson gson = new Gson();
Season season = gson.fromJson(data, Season.class);
//test
System.out.println(season.getName());
System.out.println("-------");
for (Episode ep : season.getEpisodes())
System.out.println(ep.getEpisode_number()+"\t"+ep.getName());
输出:
Season 2
-------
1 Seven Thirty-Seven
2 Grilled
3 Bit by a Dead Bee
4 Down
5 Breakage
6 Peekaboo
7 Negro Y Azul
8 Better Call Saul
9 4 Days Out
10 Over
11 Mandala
12 Phoenix
13 ABQ
<小时/>
使用的类
public class Episode {
private String air_date;
private Integer episode_number;
private String name;
private String overview;
private String still_path;
private Double vote_average;
private Integer vote_count;
//getters & setters
}
public class Season {
private String air_date;
private List<Episode> episodes = new ArrayList<Episode>();
private String name;
private String overview;
private Integer id;
private String poster_path;
private Integer season_number;
private String additionalProperties;
//getters & setters
}
关于java - 当 Regex 完全正常工作时,为什么 Java 会返回错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434553/