AndreaF AndreaF - 3 months ago 9
Java Question

Regual expression intersection to exclude a char won't work

I have some String in this form

[3 4.0:ad}
and I need to replace all whitespace and digit but
.
(that is needed to parse de float correctly)

so I have written this regular expression

\D*!.|\s+


but doesn't work and I haven't understood the right syntax I have used

\D*
to select non digit characters

!.
to exclude
.
from selection

|\s+
to select all whitespace

If I remove the intersection
!.
works so something in the way I use it is wrong.

Any suggestion?

Answer

You can use a negated character class like this:

str = str.replaceAll("[^\\d.]+", "");

[^\\d.] will match any character that is not a digit and not a DOT.

RegEx Demo

btw \D also includes whitespace so both don't need to be provided in a regex.