嘿伙计们,我一直在尝试解析 HTML 文件以从中抓取文本,时不时地,我会得到一些非常奇怪的字符,例如 à€œ
。我确定是“智能引号”或 curl 标点符号导致了我的所有问题,因此我的临时解决方案是分别搜索所有这些字符并将其替换为相应的 HTML 代码。我的问题是,是否有这样一种方法可以使用一个正则表达式(或其他东西)仅搜索字符串一次,并根据存在的内容替换它需要的内容?我现在的解决方案如下所示:
line = line.replaceAll( "“", "“" ).replaceAll( "”", "”" );
line = line.replaceAll( "–", "–" ).replaceAll( "—", "—" );
line = line.replaceAll( "‘", "‘" ).replaceAll( "’", "’" );
出于某种原因,似乎可能有更好、可能更有效的方法来做到这一点。任何意见都将不胜感激。
谢谢,
-布雷特
最佳答案
正如其他人所说;处理这些字符的推荐方法是配置编码设置。
为了进行比较,这里有一个使用正则表达式将 UTF-8 序列重新编码为 HTML 实体的方法:
import java.util.regex.*;
public class UTF8Fixer {
static String fixUTF8Characters(String str) {
// Pattern to match most UTF-8 sequences:
Pattern utf8Pattern = Pattern.compile("[\\xC0-\\xDF][\\x80-\\xBF]{1}|[\\xE0-\\xEF][\\x80-\\xBF]{2}|[\\xF0-\\xF7][\\x80-\\xBF]{3}");
Matcher utf8Matcher = utf8Pattern.matcher(str);
StringBuffer buf = new StringBuffer();
// Search for matches
while (utf8Matcher.find()) {
// Decode the character
String encoded = utf8Matcher.group();
int codePoint = encoded.codePointAt(0);
if (codePoint >= 0xF0) {
codePoint &= 0x07;
}
else if (codePoint >= 0xE0) {
codePoint &= 0x0F;
}
else {
codePoint &= 0x1F;
}
for (int i = 1; i < encoded.length(); i++) {
codePoint = (codePoint << 6) | (encoded.codePointAt(i) & 0x3F);
}
// Recode it as an HTML entity
encoded = String.format("&#%d;", codePoint);
// Add it to the buffer
utf8Matcher.appendReplacement(buf,encoded);
}
utf8Matcher.appendTail(buf);
return buf.toString();
}
public static void main(String[] args) {
String subject = "String with \u00E2\u0080\u0092strange\u00E2\u0080\u0093 characters";
String result = UTF8Fixer.fixUTF8Characters(subject);
System.out.printf("Subject: %s%n", subject);
System.out.printf("Result: %s%n", result);
}
}
输出:
Subject: String with “strange” characters
Result: String with ‒strange– characters
关于java - 一个正则表达式可以(有效地)统治所有这些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3623695/