Friday 12 May 2017

Remove square brackets from IPV6 address in Java

IpUtil.java
package com.sample;

public class IPUtil {

 /**
  * Return the ipV6Address by removing square brackets at the start and
  * ending. For the address [2001:0db8:85a3:0000:0000:8a2e:0370:7334] the
  * result is 2001:0db8:85a3:0000:0000:8a2e:0370:7334.
  * 
  * @param ipV6Address
  * @return
  */
 public static String removeSquareBrackets(String ipV6Address) {
  if (ipV6Address == null || ipV6Address.isEmpty()) {
   return null;
  }

  /* Trim leading and trailing spaces */
  ipV6Address = ipV6Address.trim();

  if (ipV6Address.startsWith("[")) {
   ipV6Address = ipV6Address.substring(1);
  }

  if (ipV6Address.endsWith("]")) {
   ipV6Address = ipV6Address.substring(0, ipV6Address.length() - 1);
  }

  return ipV6Address;
 }
}

IpUtilTest.java
package com.sample;

public class IPUtilTest {
 public static void main(String args[]){
  String address = IPUtil.removeSquareBrackets("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]");
  System.out.println(address);
 }
}



No comments:

Post a Comment