JChris
JChris

Reputation: 1678

Why Java is returning Error when Regex is totally working?

Totally working here:

{"air_date":"(.*)-.*-.*","episodes|(?:episode_|\G)number":(.*?),

Regular expression visualization

Debuggex Demo

Java returns: java.lang.NumberFormatException: null in the line 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))));
    }
}

Where response is: http://pastebin.com/m4EJ1iP5

I know it's JSON, and Regex isn't optimal. But it's required (teacher)!

Upvotes: 1

Views: 94

Answers (1)

Pshemo
Pshemo

Reputation: 124285

As you can see in your debuggex first match of your regex is

{"air_date":"2009-03-08","episodes

so you have only match in group 1 (2009-03-08 part) but group 2 is empty (which represents null) and since you are passing that null to Integer.parseInt yo are getting NumberFormatException: null. To be sure that you are handling match for episodes

episode_number":1,

test if value of group 2 isn't null like

    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))));
        }
    }

But in real world you shouldn't parse JSon with regex, but with proper parser like GSon, Jackson. Here is example of how you can do it with 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());

Output:

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

used classes

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
}

Upvotes: 1

Related Questions