Replace everything with java pairing

I am trying to add a hyperlink to stock information using a JAVA socket.

For example, this line 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 I did not expect the result. :( It was added only 005930.

Here is the conclusion.

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 are my code snippets. What am 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);
+4
source share
3 answers

I asked about this in another communique, and someone gave me an answer.

I used Matcher.replaceAll, but I needed Matcher.appendReplacement.

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

try this instead of your loop.

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

System.out.println(multipleStocks);
+2
source

replaceAll() -

, .

m.find() - Samsung, replaceAll() - Samsung LG.

m.find() false, m .

//ts = m.replaceAll("");

, Samsung LG Samsung

0
source

Source: https://habr.com/ru/post/1648230/


All Articles