1

I have one String that has multiple values in single string. I just want to remove the space after decimal point only without removing other spaces from string.

String testString = "EB:3668. 19KWh DB:22. 29KWh";

testString = testString.trim();
String beforeDecimal = testString.substring(0, testString.indexOf("."));
String afterDecimal = testString.substring(testString.indexOf("."));

afterDecimal = afterDecimal.replaceAll("\\s+", "");

testString = beforeDecimal + afterDecimal;

textView.setText(testString);

Here as in my string there is two values in single string EB:3668. 19KWh and DB:22. 29KWh. I just want to remove space after decimal point and make String like this:

EB:3668.19KWh DB:22.29KWh
Nitin Thakor
  • 535
  • 3
  • 15

4 Answers4

3

You can use 2 capture groups and match the space in between. In the replacement use the 2 groups without the space.

(\d+\.)\h+(\d+)

Regex demo

String testString="EB:3668. 19KWh DB:22. 29KWh";
String afterDecimal = testString.replaceAll("(\\d+\\.)\\h+(\\d+)","$1$2");
System.out.println(afterDecimal);

Output

EB:3668.19KWh DB:22.29KWh

Or a bit more specific pattern could be including the KWh:

\b(\d+\.)\h+(\d+KWh)

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

Just use string.replaceAll("\\. ", ".");

Thanks to Henry for pointing out I had to escape the .

Henry
  • 42,982
  • 7
  • 68
  • 84
mindoverflow
  • 730
  • 4
  • 13
1

I'm not in front of an editor right now, but wouldn't you be able to do this with the replaceAll method in a single line, without breaking it up?

var text = testString.replaceAll(". ", ".");
gmoshe27
  • 31
  • 6
0

You can remove unnecessary spaces between the decimal point and the fractional part as follows. This code also removes other extra spaces:

String testString = " EB:3668. 19KWh   DB:22. 29KWh ";

String test2 = testString
        // remove leading and trailing spaces
        .trim()
        // replace non-empty sequences of space
        // characters with a single space
        .replaceAll("\\s+", " ")
        // remove spaces between the decimal
        // point and the fractional part
        // regex groups:
        // (\\d\\.) - $1 - digit and point
        // ( )      - $2 - space
        // (\\d)    - $3 - digit
        .replaceAll("(\\d\\.)( )(\\d)", "$1$3");

System.out.println(test2); //EB:3668.19KWh DB:22.29KWh

See also: How do I remove all whitespaces from a string?