2010-09-22 41 views
0

我有類似的文字。Java Unicode Regular Expression

Every person haveue280 sumue340 ambition 

我想用正則表達式

更換ue280,ue340到\ ue280,\ ue340請問有什麼解決

在此先感謝

回答

2

像這樣的事情?

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)

+0

它不打印的Unicode ;-( – Novice 2010-09-22 19:27:22

+0

你的意思是你想實際的Unicode字符,而不僅僅是在Unicode符號前面放'\'? – aioobe 2010-09-22 19:30:20

+0

是的。是否有意義? – Novice 2010-09-22 19:53:21

0

更好的版本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(); 
相關問題