2

我本可以使用,但在这种情况下Decimal Format我必须使用。regex我有以下 String myString = "0.44587628865979384"; 我需要将它修剪到小数点后三位,所以看起来像 0.445

我尝试了以下方法:

String myString = "0.44587628865979384";
String newString = myString.replaceFirst("(^0$.)(\\d{3})(\\d+)","$1$2");
// But this does not work. What is the problem in here?
4

3 回答 3

5

不是(^0$.)。它是(\\d*.)

String newString = myString.replaceAll("(\\d*.)(\\d{3})(\\d+)", "$1$2");
于 2013-04-21T06:44:59.127 回答
3

好吧,一种合适的模式可能是“^\d\.\d{3}”,尽管您必须进行匹配才能检索它(即您正在获取您需要的内容,而不是替换您不需要的内容在你的例子中)。

...但是,您为什么要使用正则表达式来完成这项工作?

正则表达式用于查找文本中的常见模式,并让您提取/删除/列出它们。它不打算处理字符串测量

您需要使用 substring 方法将字符串切成字符子集

myString.substring(5);

如果小数点位置不同:

myString.substring(myString.indexOf(".") + 4);

记住:“有些人在遇到问题时会想“我知道,我会使用正则表达式。”现在他们有两个问题。(http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html

于 2013-04-21T06:42:25.230 回答
2

尝试这个:

String newString = myString.replaceAll"(.*\\....).*", "$1");
于 2013-04-21T06:40:46.720 回答