SachG
SachG

Reputation: 105

Regex to remove leading zero for any ipv6 address

How can I remove leading zeros from any ipv6 address.

String resultString = subjectString.replaceAll("((?::0\\b){2,}):?(?!\\S*\\b\\1:0\\b)(\\S*)", "::$2");

It's compressing to this form.

2001:0DB8:0:0:0476:: --> 2001:0DB8::0476::  

but it should remove leading zero such as:

2001:DB8::476:: 

What do I need to change in the above regex?

Upvotes: 2

Views: 2363

Answers (2)

Mike Samuel
Mike Samuel

Reputation: 120546

.replaceAll("(^|[^0-9A-Fa-f])0+([0-9A-Fa-f])", "$1$2")

will remove leading zeroes from runs of digits.

Obviously this will do bad things to numbers with decimal points or myriad separators as in "1,002,003.04".


If you want to remove not just leading zeroes from a non-zero number, but also 0, then you can use a simpler regex:

"2001:0DB8:0:0:0476::".replaceAll("\\b0+", "").equals("2001:DB8:::476::")

Upvotes: 1

Sujith PS
Sujith PS

Reputation: 4864

I can give you a simple solution :

String subjectString="2001:0DB8:0:0:0476::";
String resultString = subjectString.replaceAll("(:(0)*)|(^0+)",":");
System.out.println(resultString);

The result will be :

 2001:DB8:::476::

Upvotes: 2

Related Questions