Unicode Replacement with ASCII



我在Windows系统上创建了一个文本文件,我认为默认编码样式是ANSI,文件的内容如下所示:

This isu2019 a sample text file u2014and it can ....

我使用窗口的默认编码样式保存了此文件,尽管也有编码样式可用,如 UTF-8、UTF-16 等。

现在我想编写一个简单的 java 函数,我将在其中传递一些输入字符串并将所有 unicode 替换为相应的 ascii 值。

例如:- u2019 should be replaced with "'" u2014 should be replaced with "-" and so on.

观察:当我创建这样的字符串文字时

  String s = "This isu2019 a sample text file u2014and it can ....";

我的代码工作正常,但是当我从文件中读取它时,它不起作用。我知道在Java字符串中使用UTF-16编码。

下面是我用来读取输入文件的代码。

FileReader fileReader  = new FileReader(new File("C:\input.txt"));
BufferedReader bufferedReader = new BufferedReader(fileReader)
String record = bufferedReader.readLine();

我也尝试使用InputStream and setting the Charset to UTF-8,但结果仍然相同。

替换代码 :

public static String removeUTFCharacters(String data){      
        for(Entry<String,String> entry : utfChars.entrySet()){
            data=data.replaceAll(entry.getKey(), entry.getValue());
        }
        return data;
    }

地图:

    utfChars.put("u2019","'");
    utfChars.put("u2018","'");
    utfChars.put("u201c",""");
    utfChars.put("u201d",""");
    utfChars.put("u2013","-");
    utfChars.put("u2014","-");
    utfChars.put("u2212","-");
    utfChars.put("u2022","*");

任何人都可以帮助我理解这个问题的概念和解决方案。

将转义序列 \uXXXX 与正则表达式匹配。然后使用替换循环将该转义序列的每个匹配项替换为字符的解码值。

由于 Java 字符串文本使用 来引入转义,因此序列\用于表示。此外,Java 正则表达式语法特别处理序列u(表示 Unicode 转义(。所以必须再次逃脱,并附加\.因此,在模式中,"\\u"真正意味着"匹配输入中的u"。

要匹配数字部分,四个十六进制字符,请使用模式p{XDigit},使用额外的转义。我们希望轻松地将十六进制数提取为一个组,因此将其括在括号中以创建捕获组。因此,模式中的"(\p{XDigit}{4})"意味着"匹配输入中的 4 个十六进制字符,并捕获它们"。

在循环中,我们搜索模式的出现次数,将每个出现次数替换为解码的字符值。字符值通过分析十六进制数进行解码。 Integer.parseInt(m.group(1), 16)的意思是,"将上一场比赛中捕获的组解析为以 16 为基数的数字"。然后使用该字符创建一个替换字符串。替换字符串必须转义或引号,以防$,这在替换文本中具有特殊含义。

String data = "This is\u2019 a sample text file \u2014and it can ...";
Pattern p = Pattern.compile("\\u(\p{XDigit}{4})");
Matcher m = p.matcher(data);
StringBuffer buf = new StringBuffer(data.length());
while (m.find()) {
  String ch = String.valueOf((char) Integer.parseInt(m.group(1), 16));
  m.appendReplacement(buf, Matcher.quoteReplacement(ch));
}
m.appendTail(buf);
System.out.println(buf);

如果你可以使用另一个库,你可以使用apache commonshttps://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html

String dirtyString = "Colocaciu00F3n";
String cleanString = StringEscapeUtils.unescapeJava(dirtyString);
//cleanString = "Colocación"

最新更新