-5

Suppose i have a string: "10 000,00 EUR" or "1 000 000,00 EUR".

I would like to remove all whitespaces from the string except the last one, so the result would be like: "10000,00 EUR" or "1000000,00 EUR".

At the moment I have something like this:

String myString = "1 000 000 EUR";

myString = myString.replace("\\s(?=\\s*\\s)", "")

I assume that I should use a regex lookahead expression, which matches a whitespace that also has another whitespace following it? Any answer to solve the problem would be appreciated.

User3000
  • 65
  • 1
  • 12
  • find last space (`lastIndexOf`) and replace all spaces before that (substring); or, use split on spaces and rejoin tokens adding space fo last. But what about deleting whitespaces that are between digits? – user85421 Sep 16 '19 at 06:54
  • 1
    or just `"\\s+(?=.*\\s.*)"` that is, matches spaces that are followed by anything containing one space / for spaces between digits: `"(?<=\\d)\\s+(?=\\d)"` – user85421 Sep 16 '19 at 07:00
  • I used `"\\s+(?=.*\\s.*)"` to solve my problem. Thank you, @CarlosHeuberger – User3000 Sep 16 '19 at 07:37

2 Answers2

1

Try something like this:

Regex r = new Regex("\\s");
myString = myString.replace(r, "");

and if you want to be sure that it's not the last space:

Regex m = new Ragex("\\s\\S+^"); \\means: tha last space.
myString = myString.replace(m, "@@@@"); \\escape the last space.
myString = myString.replace(r, ""); \\delete the other spaces.
myString = myString,replace("@@@@", " "); \\put back the last space on place we marked.

The process is, for example:

myString = "100 00 0 ER"

=>"100 00 0@@@@ER" 
=>"100000@@@@ER"
=>"100000 ER"

Good Luck!

ut or
  • 46
  • 10
0

Something like:

[^\S\r\n](?=[0-9])

The idea is to match the whitespace characters except a line-feed or a carriage-return that are followed by a digit.

Refer to this answer to understand how the double-negative [^\S\r\n] works.

Demo

CinCout
  • 9,486
  • 12
  • 49
  • 67