受到此启发regex-based answer至 a unicode question我现在有以下 JavaScript 代码, 它对字符串中出现的 unicode 编码字符进行转义。
var testString = "\\u53ef\\u4ee5NonUnicode\\u544a\\u8bc9\\u6211";
print(testString)
String.prototype.unescape = function() {
return this.replace(/\\u([0-9a-f]{4})/g,
function (whole, group1) {
return String.fromCharCode(parseInt(group1, 16));
}
);
};
print(testString.unescape()) // outputs: 可以NonUnicode告诉我
我在Java(1.7)中找不到一种方法来进行这种动态正则表达式替换,只有像java.lang.String.replaceAll这样的静态方法或java.util.regex.Matcher.group ,它返回组,但无法设置它。
这在 Java 中可能吗?有什么解决办法吗?
最佳答案
使用 Matcher.appendReplacement()
非常简单和 Matcher.appendTrail()
:
// Compile the pattern
Pattern p = Pattern.compile("\\\\u([0-9a-f]{4})");
// Create a matcher for our input
Matcher m = p.matcher(testString);
// Create a buffer to hold the resulting string
StringBuffer result = new StringBuffer();
// Iterate over matches
while(m.find()) {
// Convert to UTF8 characters
int codePoint = Integer.parseInt(m.group(1), 16);
char[] chars = Character.toChars(codePoint);
// Append to buffer
m.appendReplacement(result, new String(chars));
}
// Append rest of string
m.appendTail(result);
// Display result
System.out.println(result);
你可以测试一下here .
关于javascript - Java中基于动态正则表达式的字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32562425/