Регулярное выражение Java Unicode - PullRequest
0 голосов
/ 22 сентября 2010

У меня есть такой текст.

Every person haveue280 sumue340 ambition

Я хочу заменить ue280, ue340 на \ ue280, \ ue340 на регулярное выражение

Есть ли какое-либо решение

Заранее спасибо

Ответы [ 2 ]

2 голосов
/ 22 сентября 2010

Как то так?

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 голосов
/ 22 сентября 2010

Лучшая версия обновления 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();
...