Reputation: 1154
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);
Upvotes: 4
Views: 352
Reputation: 453
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);
Upvotes: 2
Reputation: 1
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
Upvotes: 0
Reputation: 1154
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);
Upvotes: 0