【问题标题】:To remove Unicode character from String in Java using REGEX使用 REGEX 从 Java 中的字符串中删除 Unicode 字符
【发布时间】:2021-03-01 09:00:09
【问题描述】:

我有如下输入字符串。

String comment = "Good morning! \u2028\u2028I am looking to purchase a new Honda car as I\u2019m outgrowing my current car. I currently drive a Hyundai Accent and I was looking for something a
 little bit larger and more comfortable like the Honda Civic. May I know if you have any of the models currently in stock? Thank you! Warm regards Sandra";

如果注释部分中存在 Unicode 字符,如 "\u2028" 、 "\u2019" 等,我想删除它。在运行时我不知道所有额外字符会出现什么。那么处理这个问题的最佳方法是什么?

我尝试像下面这样删除给定字符串中的 unicode 字符。

Comments.replaceAll("\\P{Print}", "");

那么在注释部分中匹配 Unicode 字符的最佳方法是什么,如果存在则删除它们,否则只需将注释传递给目标系统。

谁能帮我解决这个问题?

【问题讨论】:

  • 不确定为什么要删除单引号 (\u2019)。这些是正常的字符。结果你想得到什么?
  • 嗨@WiktorStribiżew,我在将这些值(不删除Unicode 字符)推送到Salesforce 后遇到问题。这就是尝试删除的原因。下面的答案中提到的碧山,丢失了一些字符。所以还没有测试他的答案......如果你需要任何进一步的细节,请告诉我。
  • 我有一个建议:如果你只删除不是 ASCII 的符号、标点和空格怎么办?试试.replaceAll("[\\p{Z}\\p{P}\\p{S}&&[^\\p{ASCII}]]", "")。或者,如果您想将所有 Unicode 空白“规范化”为单个常规空格,并删除 Unicode 标点/符号,请尝试comment.replaceAll("(?U)\\s+", " ").replaceAll("[\\p{P}\\p{S}&&[^\\p{ASCII}]]", "")
  • 嗨@WiktorStribiżew,感谢您的建议,它工作正常。但不是将Unicode 标点符号/符号替换为空,有什么方法可以获得精确的字符。喜欢( \u2019 )变成( ' )。我们可以在运行时替换所有字符吗?将所有 Unicode 空白“标准化”为单个常规空格就可以了。
  • Python中有这样的东西。我刚刚搜索了 Java 的端口,不确定它是否正常工作,请参阅 github.com/xuender/unidecode

标签: java regex unicode non-ascii-characters


【解决方案1】:

您可以按如下顺序执行此操作:

public static void main(final String args[]) {
    String comment = "Good morning! \u2028\u2028I am looking to purchase a new Honda car as I\u2019m outgrowing my current car. I currently drive a Hyundai Accent and I was looking for something a little bit larger and more comfortable like the Honda Civic. May I know if you have any of the models currently in stock? Thank you! Warm regards Sandra";

    // remove all non-ASCII characters
    comment = comment.replaceAll("[^\\x00-\\x7F]", "");

    // remove all the ASCII control characters
    comment = comment.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "");

    // removes non-printable characters from Unicode
    comment = comment.replaceAll("\\p{C}", "");
    System.out.println(comment);
  }

【讨论】:

    【解决方案2】:

    如果你使用replace,你会丢失一些字符,例如I'm会变成Im。所以最好的就是转换。

    您可以将 Unicode 转换为 UTF-8。

    byte[] byteComment = comment.getBytes("UTF-8");
    
    String formattedComment = new String(byteComment, "UTF-8");
    

    【讨论】:

    • 嗨@Bishan,感谢您的建议,“\u2028”这将变成“?”当我尝试转换为 UTF-8 时。但在这个地方(我正在)工作。如果你有任何顾虑,请告诉我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2019-01-01
    • 2016-02-16
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多