java 操作 IP 地址 - 在 '.' 上拆分字符串 特点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15310505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manipulating IP addresses - split string on '.' character
提问by WassiM ZgheiB
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 : ("\\.")
?
那么为什么在 IPv4 地址中拆分点是这样完成的:("\\.")
?
回答by Boris the Spider
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
:
你需要转义“。” assplit
需要一个正则表达式。但是您还需要将转义符转义为“\”。在 java 中不起作用String
:
String [] split = address.split("\.");
This is because the backslash in a java String
denotes the beginning of a character literal.
这是因为 java 中的反斜杠String
表示字符文字的开头。
回答by sol4me
You should split like this, small tip use Pattern.compile as well
你应该像这样拆分,小技巧也使用Pattern.compile
String address = "192.168.1.1";
String[] split = address.split("\.");// you can replace it with private static final Pattern.