Christian Sakai Christian Sakai - 4 months ago 10
Java Question

Java Regex to Strip Leading & Trailing Zeros with Spaces

Strings of integers such as below, in Java how do I strip the leading and trailing zeros and make it look like:


  • 0 0 1 2 3
    becomes
    1 2 3

  • 0 -2 4 0 0 0
    becomes
    -2 4

  • 0 3 0 -4 0 0
    becomes
    3 0 -4

  • 0 10 9 0 0 20 0
    becomes
    10 9 0 0 20


Answer

This regex does what you require, as far as I can see.

string pattern = "^[ 0]*|( |(?<!\d)0)*$";
str.replaceAll(pattern, "");

To explain: the expression is in two parts, seperated by the first |. The first part, ^[ 0]*, simply looks for 0 or more spaces or zeros at the beginning of a line/string (^ denotes start of line/string).

The second part, ( |(?<!\d)0)*$, is a bit more complex, because of the special case where the last non-zero number in a line ends with the digit zero. This part looks for zero or more occurances of either space or (?<!\d)0), which means zero not preceded by a digit. The ?<!\d part is called a negative lookbehind. Lastly comes $, which denotes end of line/string.

Comments