-1

I am using Jsoup in my project and i am try to get understand what these lines of code in my HTMLparser.java is step by step doing:

static List<LinkNode> toLinkNodeObject(LinkNode parentLink, Elements tagElements, String tag) {
    List<LinkNode> links = new LinkedList<>();
    for (Element element : tagElements) {
        if(isFragmentRef(element)){
            continue;
        }

        String absoluteRef = String.format("abs:%s", tag.contains("[") ? tag.substring(tag.indexOf("[") + 1, tag.length()) : "href");
        String url = element.attr(absoluteRef);

        if(url!=null && url.trim().length()>0) {
            LinkNode link = new LinkNode(url);
            link.setTag(element.tagName());
            link.setParentLink(parentLink);
            links.add(link);
        }
    }
    return links;
}

Can you tell me what "abs:%s" regex in this line is doing ?

 String absoluteRef = String.format("abs:%s", tag.contains("[") ? tag.substring(tag.indexOf("[") + 1, tag.length()) : "href");
medo0070
  • 511
  • 1
  • 5
  • 21

1 Answers1

2

Lets say that tag has the following value:

tag = "blah, blah, [medo0070";

then the line in question

String absoluteRef = String.format("abs:%s", tag.contains("[") ? tag.substring(tag.indexOf("[") + 1, tag.length()) : "href")

will assign

abs:medo0070

to absoluteRef because the tag variable contains the '[' character. If tag had the value

tag = "blah, blah, medo0070";

then absoluteRef would be given the value

abs:href

because the tag variable doesn't contain the '[' character.

The Ternary operator (see here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html) works like this:

a ? b : c;

is equivalent to

if (a) {
    b;
}
else {
    c;
}

In your example, a is tag.contains("["), b is tag.substring(tag.indexOf("[") + 1, tag.length()) and c is "href".

JamesB
  • 7,774
  • 2
  • 22
  • 21
  • 1
    Thanks for your answer. I wander if you know what **indexOf("[") + 1** is do. I mean what "plus one"do to the tag. Can you tell me that ? – medo0070 Mar 02 '15 at 01:26
  • 1
    It's String.subString(). http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int) – Wilts C Mar 02 '15 at 01:44