Christian Sakai - 3 months ago 8x

Java Question

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

- becomes
`0 0 1 2 3`

`1 2 3`

- becomes
`0 -2 4 0 0 0`

`-2 4`

- becomes
`0 3 0 -4 0 0`

`3 0 -4`

- becomes
`0 10 9 0 0 20 0`

`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.

Source (Stackoverflow)

Comments