Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating IP addresses - split string on '.' character

Tags:

java

regex

String address = "192.168.1.1";

I want to split the address and the delimiter is the point. So I used this code:

String [] split = address.split(".");

But it didn't work, when I used this code it works:

String [] split = address.split("\\.");

so why splitting the dot in IPv4 address is done like this : ("\\.") ?

like image 686
WassiM ZgheiB Avatar asked Jan 15 '23 00:01

WassiM ZgheiB


2 Answers

You need to escape the "." as split takes a regex. But you also need to escape the escape as "\." won't work in a java String:

String [] split = address.split("\\.");

This is because the backslash in a java String denotes the beginning of a character literal.

like image 97
Boris the Spider Avatar answered Jan 19 '23 10:01

Boris the Spider


You should split like this, small tip use Pattern.compile as well

String address = "192.168.1.1";
String[] split = address.split("\\.");// you can replace it with private static final Pattern.
like image 31
sol4me Avatar answered Jan 19 '23 10:01

sol4me