Java Unicode正则表达式
-
04-10-2019 - |
题
我有一些这样的文字。
Every person haveue280 sumue340 ambition
我想将UE280,UE340替换为 ue280, ue340,带有正则表达式
有没有解决方案
提前致谢
解决方案
这样的东西?
String s = "Every person haveue280 sumue340 ambition";
// Put a backslash in front of all all "u" followed by 4 hexadecimal digits
s = s.replaceAll("u\\p{XDigit}{4}", "\\\\$0");
这导致
Every person have\ue280 sum\ue340 ambition
不确定您是在追求什么,但也许是这样的:
static String toUnicode(String s) {
Matcher m = Pattern.compile("u(\\p{XDigit}{4})").matcher(s);
StringBuffer buf = new StringBuffer();
while(m.find())
m.appendReplacement(buf, "" + (char) Integer.parseInt(m.group(1), 16));
m.appendTail(buf);
return buf.toString();
}
(根据AXTAVT非常好的替代方案进行更新。制作CW。)
其他提示
AioObe更新的更好版本:
String in = "Every person haveue280 sumue340 ambition";
Pattern p = Pattern.compile("u(\\p{XDigit}{4})");
Matcher m = p.matcher(in);
StringBuffer buf = new StringBuffer();
while(m.find())
m.appendReplacement(buf, "" + (char) Integer.parseInt(m.group(1), 16));
m.appendTail(buf);
String out = buf.toString();
不隶属于 StackOverflow