String.split (String pattern) Java method does not work properly

I use String.split () to separate some strings as IP addresses, but them returning an empty array, so I fixed my problem using String.substring () but I wonder why it doesn’t work as intended, my code:

// filtrarIPs("196.168.0.1 127.0.0.1 255.23.44.1 100.168.100.1 90.168.0.1","168");
public static String filtrarIPs(String ips, String filtro) {
    String resultado = "";
    String[] lista = ips.split(" ");
    for (int c = 0; c < lista.length; c++) {
        String[] ipCorta = lista[c].split("."); // Returns an empty array
        if (ipCorta[1].compareTo(filtro) == 0) {
            resultado += lista[c] + " ";
        }
    }
    return resultado.trim();
}

He must return String[] as {"196"."168"."0"."1"}....

+3
source share
5 answers

Your expression

lista[c].split(".")

will split the first line "196.168.0.1"into any character ( .), because String.split takes a regular expression as an argument.

, , split .

, :

String[] tiles = "aaa".split("a");

, [ , , ]. - , , [].

:

String[] tiles = "aaab".split("a");

b [ , , , "b"] , .

, , :

lista[c].split("\\.")
+3

split . '' . split , : split("\\.").

+8

String[] ipCorta = lista[c].split("\\.");

in regular expressions .matches almost any character. If you want to combine a point, you need to avoid it \\..

+6
source

String.split()takes a regex as a parameter, so you need to avoid a period (which matches something). Therefore use split("\\.").

+1
source

This may help you:

 public static void main(String[] args){
    String ips = "196.168.0.1 127.0.0.1 255.23.44.1 100.168.100.1 90.168.0.1";
    String[] lista = ips.split(" ");
    for(String s: lista){
        for(String s2: s.split("\\."))
            System.out.println(s2);
    }
}
+1
source

All Articles