加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

算法基础——2.4正则表达式初步

发布时间:2020-12-13 23:07:17 所属栏目:百科 来源:网络整理
导读:例一: /* 串的处理中直接使用正则的API split match replaceAll*/public class T1{public static void main(String[] args){//把串中的表示日期的子串变换成另一种日期表达格式String s = "abc,kkk 2015-08-19 ttk";s = s.replaceAll("([0-9]{4})-([0-9]{2}

例一:

/*
   串的处理中直接使用正则的API
   split
   match
   replaceAll
*/

public class T1
{
	public static void main(String[] args)
	{
		//把串中的表示日期的子串变换成另一种日期表达格式
		String s = "abc,kkk 2015-08-19 ttk";
		s = s.replaceAll("([0-9]{4})-([0-9]{2})-([0-9]{2})","$2/$3 $1年");
		System.out.println(s);
		
		/*
		// 判断一个串,是否为Excel地址的表达格式
		String s = "A3";
		System.out.println(s.matches("[A-F]{1,2}[0-9]{1,5}"));
		*/
		
		/*  
		// 被一个或多个空格分割的字符串分离出来
		String s = "ab   xyz  kkk";
		
		//String[] ss = s.split(" {1,}");
		String[] ss = s.split(" +");
		for(int i=0; i<ss.length; i++){
			System.out.println(ss[i]);
		}
		*/
		
	}
}

例二;

方法一:

/*第02讲-正则表达式初步_分散字符串
请把下列字符串分散为数字和字符构成的串
String s1 = "abc1234xyz667kkmd764tttt";

串由字母和数字间隔构成,要分离出所有的字母段和数字段,即:
abc
1234
xyz
667
kkmd
764
tttt
 */

public class C4 {
	public static void main(String[] args) {
		String s1 = "abc1234xyz667kkmd764tttt";
		String []s2 = s1.split("[0-9]{1,}");
		String []s3 = s1.split("[a-z]{1,}");
		
		int i;
		for(i = 0; i < s2.length && i < s3.length; ++i)
		{
			if(!s2[i].equals(""))
				System.out.println(s2[i]);
			if(!s3[i].equals(""))
				System.out.println(i+s3[i]);
		}
		
		if(i == s2.length){//s2已经输出完,继续输出s3
			for(int j = i; j < s3.length; ++j){
				if(!s3[i].equals(""))
					System.out.println(i+s3[i]);
			}
		}
		else{//s3已经输出完,继续输出s2
			for(int j = i; j < s2.length; ++j){
				if(!s2[i].equals(""))
					System.out.println(i+s2[i]);
			}
			
		}
	}

}

方法二:
public class FenLi
{
	public static void main(String[] args)
	{
		String s = "abc1234xyz667kkmd764tttt";
		
		s = s.replaceAll("([a-zA-Z])([0-9])","$1,$2");
		s = s.replaceAll("([0-9])([a-zA-Z])",$2");
		
		System.out.println(s);
		
		// 然后正常使用split进行分割就可以了。
		s = s.split(",");
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读