【问题标题】:replace any non-ascii character in a string in java替换java中字符串中的任何非ascii字符
【发布时间】:2013-09-08 13:15:35
【问题描述】:

如何在 java 中将-lrb-300-rrb-┬á922-6590 转换为-lrb-300-rrb- 922-6590

尝试了以下方法:

t.lemma = lemma.replaceAll("\\p{C}", " ");
t.lemma = lemma.replaceAll("[\u0000-\u001f]", " ");

我可能遗漏了一些概念性的东西。将感谢任何指向解决方案的指针。

谢谢

【问题讨论】:

  • “unicode”是什么意思?任何非ASCII?
  • 我假设那些嵌入的特殊字符是 unicode...
  • 你所说的“unicode”是什么意思?根据standard definition,该字符串中的所有字符都是unicode,而不仅仅是“┬á”。

标签: java regex unicode


【解决方案1】:

尝试下一个:

str = str.replaceAll("[^\\p{ASCII}]", " ");

顺便说一句,\p{ASCII} 都是 ASCII:[\x00-\x7F]

另一方面,您需要使用Pattern 常量以避免每次都重新编译表达式。

private static final Pattern REGEX_PATTERN = 
        Pattern.compile("[^\\p{ASCII}]");

public static void main(String[] args) {
    String input = "-lrb-300-rrb- 922-6590";
    System.out.println(
        REGEX_PATTERN.matcher(input).replaceAll(" ")
    );  // prints "-lrb-300-rrb- 922-6590"
}

另见:

【讨论】:

【解决方案2】:

假设您只想保留a-zA-Z0-9 和标点符号,您可以这样做:

t.lemma = lemma.replaceAll("[^\\p{Punct}\\w]", " "));

【讨论】:

  • t.lemma = lemma.replaceAll("[^\\p{ASCII}]", ""); 怎么样?
  • 在这种情况下也可以,但它包含更多字符。我不确定 OP 想要什么。
猜你喜欢
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
  • 2015-02-27
  • 2013-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
相关资源
最近更新 更多