Guava 的 Charmatcher 方法(例如 javaDigit())的替代方法?

Alternative for Guava's Charmatcher methods such as javaDigit()?

我使用 Guava 的 CharMatcher 已经很长时间了,它对所有方面都非常有效。现在我看到其中的大部分方法现在在 Guava 27.0.1

中已弃用

文档说的是"Deprecated. Many digits are supplementary characters; see the class documentation." 但是看了class文档后,我还是一头雾水。大多数时候,当一个方法被弃用时,他们会告诉你另一种做事的方法,但是,这一次,我觉得文档基本上是在说 "This class doesn't really work correctly, so don't use it".

正确的方法是什么,例如只保留字符串的数字?在我可以简单地做之前:

String inputString = "abc123def456";
String outputString = CharMatcher.javaDigit().retainFrom(inputString);

该方法的 Javadoc 声明:

@deprecated Many digits are supplementary characters; see the class documentation.

这意味着除了您通常使用的从 0 到 9 的数字之外,还可以匹配其他字符。

在 Guava 中有两种内置方法:digit() and javaDigit(). The former matches "BMP digit according to Unicode" specs, the latter matches "BMP digit according to Character#isDigit()”。它们中的每一种都匹配怪异的字符,例如 Devanagari 或 Fullwidth 数字(我什至不会 link 他们 ;)),这很少是用户想要的,并且可能会产生误导。

这就是为什么(番石榴作者)首选的方式是明确的(稍后在 javadoc 中说明):

If you only care to match ASCII digits, you can use CharMatcher#inRange('0', '9').

在您的情况下,只需使用:

String outputString = CharMatcher.inRange('0', '9').retainFrom(inputString);

一个更通用的解决方案,因为我需要一个:用 CharMatcher.forPredicate, and pass in one of the character classification methods from the Java Character class 替换弃用的方法。

CharMatcher.forPredicate(Character::isDigit).retainFrom(inputString)