String.split returning null when using a dot

后端 未结 3 1366
忘掉有多难
忘掉有多难 2020-12-06 09:41

I got this simple code:

String ip = \"1.2.3.4\";
String[] ipArray = ip.split(\".\");
System.out.println(ipArray[1]);

And ipArray

相关标签:
3条回答
  • 2020-12-06 10:07

    Pattern.quote(String) can also be used to quote the whole string. This returns a pattern which will be interpreted literally, special characters will have no special meaning. This might be overkill in this case, but sometimes it can be useful.

    0 讨论(0)
  • 2020-12-06 10:09

    Use ip.split("\\."); and your problems will be solved. The problem is that String#split receives a regular expression, the dot (.) symbol is a special character in regular expressions, so you need to escape it for it to be interpreted as a plain dot, also as the backslash is an escape character in Java, you have to escape it too.

    0 讨论(0)
  • 2020-12-06 10:09

    . is a special character in regular expressions, which is what is used to split a string.

    To get around this, you need to escape the .. That leads us to \. Unfortunately, \ is ALSO a special character in the java string, so that must also be escaped, to make \\.

    Our "final" result is ip.split("\\.");

    In a related issue, the whole process can be averted entirely. There's no sense in doing something that a standard library already has done for us.

    Consider the following

    byte[] ipOctets = InetAddress.getByName(ip).getAddress();
    

    The only issue here is to remember that if you want the int value, you have to extract it with & like int octet = ipOctets[0] & 0xFF;

    0 讨论(0)
提交回复
热议问题