截取ip地址字符串?

cqhweb 2009-05-08 10:02:40
现有一字符串:

http://10.150.1.5/names.nsf

希望截取后的结果为: http://10.150.1.5/



注意IP地址:可能会变 http://xxx.xxx.xxx.xxx/
...全文
203 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangkaixin1226 2009-05-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 jinxfei 的回复:]
正则表达式:

Java codepublicstaticvoidmain(String[] args){
Pattern p=Pattern.compile("http://\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
String str="http://10.150.1.5/names.nsf";
Matcher m=p.matcher(str);if(m.find()){
System.out.println("你要的结果:"+m.group());
}
}
[/Quote]
每一段都是一到三个数字,1楼的方法正解
noone_1983 2009-05-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 jinxfei 的回复:]
正则表达式:


Java code
public static void main(String[] args){
Pattern p=Pattern.compile("http://\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
String str="http://10.150.1.5/names.nsf";
Matcher m=p.matcher(str);
if(m.find()){
System.out.println("你要的结果:"+m.group());
}
}
[/Quote]
正解
jinxfei 2009-05-09
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 justinavril 的回复:]
引用 1 楼 jinxfei 的回复:
正则表达式:


Java code
public static void main(String[] args){
Pattern p=Pattern.compile("http://\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
String str="http://10.150.1.5/names.nsf";
Matcher m=p.matcher(str);
if(m.find()){
System.out.println("你要的结果:"+m.group());
}
}

你的这个是能匹…
[/Quote]

恩,就是要的吹毛求疵的精神。
zhangpeixv 2009-05-09
  • 打赏
  • 举报
回复
用正则了
呵呵
justinavril 2009-05-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 jinxfei 的回复:]
正则表达式:


Java code
public static void main(String[] args){
Pattern p=Pattern.compile("http://\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
String str="http://10.150.1.5/names.nsf";
Matcher m=p.matcher(str);
if(m.find()){
System.out.println("你要的结果:"+m.group());
}
}
[/Quote]
你的这个是能匹配IP地址,但是有一个问题就是,无效的IP地址你这个正则没法过滤,比如:555.555.555.555。当然了,吹毛求疵了。

当然了 你可以把IP前三个字段写在一起:

"(\\d{1,3}\\.){3}\\d{1,3}"
jinxfei 2009-05-08
  • 打赏
  • 举报
回复
正则表达式:


public static void main(String[] args){
Pattern p=Pattern.compile("http://\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
String str="http://10.150.1.5/names.nsf";
Matcher m=p.matcher(str);
if(m.find()){
System.out.println("你要的结果:"+m.group());
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧