Question

Imagine this array.

data[0] = <a href="/item/main.nhn?code=002530" class="tltle">Marine</a>
data[1] = <a href="/item/main.nhn?code=068270" class="tltle">Medic</a>
data[2] = <a href="/item/main.nhn?code=053800" class="tltle">Firebat</a>

I want to bring attribute of code (002530, 068270, 053800) to code[] array. and pure text (Marine, Medic, Firebat). Like this:

code[0] = 002530
code[1] = 068270
code[2] = 053800
text[0] = Marine
text[1] = Medic
text[2] = Firebat

How can I do that? Should I have to use StringTokenizer? or split()? I don't know how to get that. Please Help me. Thank you.

Was it helpful?

Solution

You can use regular expressions, See this Voguella tutorial

".*code=([0-9]*).*>([A-Za-z]*)<.*"

And a code like this:

    String[] array = new String[3];
    array[0] = "<a href=\"/item/main.nhn?code=002530\" class=\"tltle\">Marine</a>";
    array[1] = "<a href=\"/item/main.nhn?code=068270\" class=\"tltle\">Medic</a>";
    array[2] = "<a href=\"/item/main.nhn?code=053800\" class=\"tltle\">Firebat</a>";

    Pattern pattern = Pattern.compile(".*code=([0-9]*).*>([A-Za-z]*)<.*");

    for (int i = 0; i < array.length; i++) {
        String string = array[i];
        Matcher ma = pattern.matcher(string);
        System.out.println("Code " + i + ":" + ma.replaceFirst("$1"));
        System.out.println("Text " + i + ":" + ma.replaceFirst("$2"));
    }

see a working example in: http://ideone.com/WJIjM5

Obs: remember to escape " in your strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top