-5

Android development.

The response is like this:

 <div id="Song" data-airtime="14:12:52" data-runtime="207.25">
 <span id="artist">Weeknd</span><span id="titl">Can't Feel My Face</span></div>

I need the artist, and the title. The problem with the substring indexof(value) method, that the response lenght not a fixed sized, for example, if the artist name is longer.. etc..

How to substring or split to match the correct form?

I tried the left side is ok.

 String left = name.substring(name.indexOf("artist\">")+8);
Janos
  • 197
  • 4
  • 16

2 Answers2

1

You don't want to split the string up by hand. As you see, lengths are variable and you can't predict many things.

The link below has many solutions to parsing HTML.

How to use regular expressions to parse HTML in Java?

Shmuel
  • 3,916
  • 2
  • 27
  • 45
0

You could parse XML or use regex. To keep things simple, I would suggest regex. Here is how you can use it:

Pattern pattern = Pattern.compile("<span id=\"artist\">(.*?)<\\/span><span id=\"titl\">(.*?)<\\/span>");
Matcher m = pattern.matcher(input);
if (m.find() {
    MatchResult result = m.toMatchResult();
    String artist = result.group(1);
    String title = result.group(3);
}

Where input is the XML you have.

In regex, patterns inside parenthesis represent capture groups. They allow you to extract results from a match. However, note that in the code you retrieve the group 1 and 3. That's because for every capture group you have the own capture group and the result. So, result.group(0) would be the pattern for the first group and result.group(2) would be the pattern for the second group.

Rafael Caetano
  • 46
  • 1
  • 2
  • 4