[英]Java replace smileys in string
我有以下功能來替換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);
我收到此錯誤: java.util.regex.PatternSyntaxException: Unknown character property name {} near index 4 &:\\P
任何想法我做錯了什么?
僅需轉義括號,而無需改寫原義字符。 所以:
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'/>");
注意第二行的更改。
基本上,如果您不對右括號進行轉義,則解析器會感到困惑,因為它認為它錯過了右括號。 因此,您必須轉義括號。 另一方面,普通的字母(在您的示例中為D)不需要轉義,因為它們不構成正則表達式構造的一部分。
該代碼段應該正常工作,除了如果第二個模式打算匹配一個笑臉而不是一個&
再跟一個:
,然后是一個非數字字符,則應該匹配。
smileys.put("&:D", "<img src='http://url.com/assets/2.png'/>");
對我來說很好
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;
}
}
輸出-
<img src='http://url.com/assets/1.png'/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.