0

Here is a nice short example to filter string as decimal:

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

, which makes 12.334.78

But how to filter this second decimal part? I have a string valued 12345.67 doll. (notice the dot at the end). So i need only 12345.67

Sorry for not just commenting that Óscar López's answer because have not enough reputation.

Community
  • 1
  • 1
kolyaseg
  • 535
  • 5
  • 13
  • Two numbers can be extracted from `12.334.78`. 12.344 and .78 is that what you need? –  Jan 01 '15 at 18:44
  • sln, no. A string can be of any kind, the given one is just for example. The thing is i have to get only one dot. – kolyaseg Jan 01 '15 at 20:34

2 Answers2

0

You could implement Negative Lookahead to remove any . that does not precede a digit.

str = str.replaceAll("[^\\d.]|\\.(?!\\d)", "");
Ideone Demo
hwnd
  • 69,796
  • 4
  • 95
  • 132
0

I looked it up but not sure. Android regex (like Java) can use the
\G assertion, which means start at the end of the last match position.

Your problem can't be solved with a single regex, however it can be done with
two regex.

It's simple really.

Both are used in a replace all situation.

The first just clears out whatever you don't want.
Using your example its.

Find: "[^\\d.]+"
Replace: ""

The second is:
Find: "(?:(?!\\A)\\G|(\\.))([^.]*)\\."
Replace: "$1$2"

The last regex removes all the Dots after the first one (but NOT the first one)
Here is the breakdown of this regex:

 (?:
      (?! \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

Input:

a12.334tyz.78x  

Output:

12.33478