将字符串过滤为十进制数

Filter string as decimal number

Here 是将字符串过滤为十进制的一个很好的简短示例:

String str = "a12.334tyz.78x";
str = str.replaceAll("[^\d.]", "");

,这使得 12.334.78

但是如何过滤这个小数点后第二位呢?我有一个字符串 valued 12345.67 doll. (注意末尾的点)。所以我只需要 12345.67

很抱歉,因为没有足够的声誉而没有评论 Óscar López 的回答。

您可以实施 Negative Lookahead 以删除任何不在数字之前的 .

str = str.replaceAll("[^\d.]|\.(?!\d)", "");
Ideone Demo

我查了一下,但不确定。 Android 正则表达式(如 Java)可以使用
\G断言,意思是从上次匹配结束的位置开始。

您的问题不能用一个正则表达式解决,但是可以用
解决 两个正则表达式。

真的很简单。

两者都用于替换所有的情况。

第一个只是清除你不想要的东西。
使用你的例子。

查找:"[^\d.]+"
替换:""

第二个是:
查找:"(?:(?!\A)\G|(\.))([^.]*)\."
替换:""

最后一个正则表达式删除了第一个之后的所有点(但不是第一个)
这是此正则表达式的细分:

 (?:
      (?! \A )             # Not at BOS
      \G                   # Start at end of last match position
   |                     # or, 
      ( \. )               # (1), One time, The first Dot in the string
 )
 ( [^.]* )            # (2), Optional any chars
 \.                   # Until we find the next extra Dot to remove

输入:

a12.334tyz.78x  

输出:

12.33478