简体   繁体   中英

Java replace smileys in string

I have the following function to replace smileys in a String :

public String replaceSmileys(String text) {
    for (Entry < String, String > smiley: smileys.entrySet())
        text = text.replaceAll(smiley.getKey(), smiley.getValue());
    return text;
}

static HashMap < String, String > smileys = new HashMap < String, String > ();
smileys.put("&:\\)", "<img src='http://url.com/assets/1.png'/>");
smileys.put("&:\\D", "<img src='http://url.com/assets/2.png'/>");
smileys.put("&;\\)", "<img src='http://url.com/assets/3.png'/>");


String sml = replaceSmileys(msg);

Im getting this error: java.util.regex.PatternSyntaxException: Unknown character property name {} near index 4 &:\\P

Any ideas what im doing wrong?

Only your parentheses need to be escaped, not your literal characters. So:

smileys.put("&:\\)", "<img src='http://url.com/assets/1.png'/>");
smileys.put("&:D", "<img src='http://url.com/assets/2.png'/>");
smileys.put("&;\\)", "<img src='http://url.com/assets/3.png'/>");

Note change on second line.

Basically, if you don't escape the close-parentheses, the parser gets confused because it thinks it has missed an open-parenthesis. So you must escape the parentheses. On the other hand, plain-old letters (D in your example) don't require escaping, since they don't form a part of a regex construct.

该代码段应该正常工作,除了如果第二个模式打算匹配一个笑脸而不是一个&再跟一个: ,然后是一个非数字字符,则应该匹配。

    smileys.put("&:D", "<img src='http://url.com/assets/2.png'/>");

Its working fine for me

public class Test {
    public static void main(String[] args) {
        String sml = replaceSmileys("&:)");
        System.out.println(sml);
    }

    static String replaceSmileys(String text) {
        HashMap < String, String > smileys = new HashMap < String, String > ();
        smileys.put("&:\\)", "<img src='http://url.com/assets/1.png'/>");
        smileys.put("&:D", "<img src='http://url.com/assets/2.png'/>");
        smileys.put("&;\\)", "<img src='http://url.com/assets/3.png'/>");
        for (Entry < String, String > smiley: smileys.entrySet())
            text = text.replaceAll(smiley.getKey(), smiley.getValue());
        return text;
    }
}

Output -

<img src='http://url.com/assets/1.png'/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM