Christian Sakai
Christian Sakai

Reputation: 979

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:

Upvotes: 2

Views: 1120

Answers (1)

Magnus Buvarp
Magnus Buvarp

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

Related Questions