replaceAll How to do repetition

Asked

Viewed 88 times

0

want to make a replaceAll from 0.0 to 9999.9999 and wanted to know if there’s another way besides adding 1 by 1?

I was doing like this

fim = fim.replaceAll("0.0", "0.0f");
        fim = fim.replaceAll("0.1", "0.1f");
        fim = fim.replaceAll("0.2", "0.2f");
        fim = fim.replaceAll("0.3", "0.3f");
        fim = fim.replaceAll("0.4", "0.4f");
        fim = fim.replaceAll("0.5", "0.5f");
        fim = fim.replaceAll("0.6", "0.6f");
        fim = fim.replaceAll("0.7", "0.7f");
        fim = fim.replaceAll("0.8", "0.8f");
        fim = fim.replaceAll("0.9", "0.9f");

1 answer

5

If it’s to add the f at the end of the number just use regular expression () getting something like:

\d+\.\d+

The \d looks for a digit, d+ looks for a digit "sequence", the \. looks for a point after the number and next \d+ the same, in Java would look like this:

fim = fim.replaceAll("\\d+\\.\\d+", "$0f");

Needs two \\ because of the escape of Java itself inside strings.

If it is only the number will work well, but if it is in the middle of a text this may not work, for example if you have compound words, like:

foo0.0bar

Which though unlikely, is not entirely impossible, so in this case use the meta-character \b at the beginning and end of the regex, example:

fim.replaceAll("\\b\\d+\\.\\d+\\b", "$0f");

The $0 is who takes the whole group in a regex, see the online example on repl it..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.