[英]Dynamic regex based string replacement in Java
受此基于regex 的unicode问题 答案的启发,我现在拥有以下javascript代码,该代码避免了字符串中未编码的编码字符出现。
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);
您可以在这里进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.