4

I'm trying to add hyperlink on stock information using JAVA matcher.

For example, this string will be changed

How do you think about Samsung and LG? I think Samsung is good.

to

How do you think about <a href="" kospi-code="005930">Samsung</a> and <a href="" kospi-code="003550">LG</a>? I think <a href="" kospi-code="005930">Samsung</a> is good.

But, result was not I expected. :( It was only added 005930.

Here is output.

How do you think about <a href="" kospi-code="005930">Samsung</a> and <a href="" kospi-code="005930">LG</a>? I think <a href="" kospi-code="005930">Samsung</a> is good.

Here is my code snippets. What did I wrong?

String multipleStocks = "How do you think about Samsung and LG? I think Samsung is good.";
Pattern p = Pattern.compile("Hansum|LG|Samsung");
Matcher m = p.matcher(multipleStocks);

HashMap<String, String> stocks = new HashMap<String, String>();

stocks.put("Hansum", "020000");
stocks.put("Samsung", "005930");
stocks.put("LG", "003550");
String ts = null;

while(m.find()){
    System.out.println(m.group());
    ts = m.replaceAll("<a "+stocks.get(m.group(0))+">$0</a>"); 
}
System.out.println(ts);

3 Answers 3

2

try this in place of your loop.

for (String key : stocks.keySet()) {
    multipleStocks=multipleStocks.replaceAll(key, "<a "+stocks.get(key)+">$0</a>");
}

System.out.println(multipleStocks);
Sign up to request clarification or add additional context in comments.

2 Comments

Appricate your answer. I found another solution but your's works well. Thank you @rht.
Oh, I found a problem that is existing similar keys in stocks. For instance, if LG Elotronics is exists in stocks, then link will be <a href="" kospi-code="005930"><a href="" kospi-code="066570">LG</a> Eloctronics</a>
0

I asked this to other communitiy and someone gave me an answer.

I used Matcher.replaceAll but what had needed to me was Matcher.appendReplacement.

    while(m.find()){
        m.appendReplacement(sb, "<a "+stocks.get(m.group(0))+">$0</a>");
    }
    m.appendTail(sb);

1 Comment

@Gab It needs 2 days for accept own answer. Thank you Gab.
0

replaceAll() is

Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.

the first loop m.find() is matcher Samsung , but replaceAll() is matcher Samsung and LG .

the second loop m.find() will return false,because m is changed.

you can annotation this code // ts = m.replaceAll("");

and execute , will print Samsung LG Samsung

1 Comment

Thank you but I want to attach html tag to such as Samsung and LG, not want to watch what has printed out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.