现在的位置: 首页 > 综合 > 正文

Java 正则表达式--匹配字符获取、IP地址排序

2013年08月10日 ⁄ 综合 ⁄ 共 1214字 ⁄ 字号 评论关闭

 

package Regex;
import java.util.regex.*;
import java.util.*;
public class RegexGet {

		public static void main(String args[])
		{
			//get();
			//test_1();
			test_2();
		}
		
		
		public static void get()
		{
			String str=  "good good study,day day up ";
			String regex ="\\b[a-z]{4}\\b";  //取由四个字符组成的单词
			Pattern p = Pattern.compile(regex);
		//	System.out.println(p);
			Matcher m = p.matcher(str);
			
			while(m.find())
			{
				System.out.println(m.group()+m.start()+"---"+m.end());
			}
		}
		
		/*
		 * 		练习1
		 * 	 将 我我......要要要要要.......学......学学.......编编..........程 转成
		 * 		我要学编程 
		 * 
		 * */
		
		public static void test_1()
		{
			String str = "我我......要要要要要.......学......学学.......编编..........程";
			// 先将里面的点全部替换掉
			
			String regex ="\\.+";
			str=str.replaceAll(regex,"");
			
			// 下面将重复出现的字符只保留一个
			 regex="(.)\\1+";
			 str=str.replaceAll(regex,"$1");
			System.out.println(str);
			
		}
		
		/*		练习二
		 * 		对 给出的IP 地址进行排序
		 * 192.68.1.254 102.49.23.13 10.10.10.10 2.2.2.2. 8.109.90.30
		 * 
		 */
		
		public static void test_2()
		{
			String ip = "192.68.1.254 102.49.23.13 10.10.10.10 2.2.2.2 8.109.90.30";
			
			// 先对IP每一位都添加两个0
			String regex = "(\\d+)";
			ip = ip.replaceAll(regex,"00$1");
			
			// 再将IP地址只保留三位
			regex = "0*(\\d{3})";
			ip = ip.replaceAll(regex,"$1");
			
			// 下面进行切割
			String[] result = ip.split(" +");
			Arrays.sort(result);
			System.out.println("after");
			for(int i =0;i<result.length;i++)
				result[i]=result[i].replaceAll("0*(\\d+)","$1");  // 将前面的0 去掉
			for(String s : result)
				System.out.println(s);
		}
}

抱歉!评论已关闭.