Reputation: 979
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
Upvotes: 2
Views: 1120
Reputation: 976
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.
Upvotes: 3