`

JAVA用正则表达式处理字符串(基础)

阅读更多

正则表达式的内容很多,但是抛开那些复杂的,最基本的总结起来也就是下面几点:

1.一个中括号无论里面有什么都是代表一个字符.

2.正则表达式中可以用逻辑符号,比如&与,|或,^非.

3.再就是数量词,放在一个字符的后面,?表示这个字符一次都没有或者是有一次,*表示0额以上,+表示一个以上,{n}表示有n个.

4.()用来分组

 

然后便是用正则表达式来处理字符串了:

1.字符串的切割

//字符串的切割
String str = "zhangsan,lisi,wangwu,mazi";
//定义正则表达式
rex = ",";
//用正则表达式去处理字符串str
test(str, rex);

 其中test方法为:

public static void test(String str,String rex){
		//用正则表达式切割字符串
		String[] strs = str.split(rex);
		//遍历切割出来的字符串数组
		for(String s:strs){
			System.out.println(s);
		}
	}

 2.字符串的替换

 (1)将字符串中的5替换成#

//5换成#
str = "asdsad5dfsdf5asdvgnhg55hjmjh5";
rex = "5";
newstr = "#";
test(str, rex, newstr);

 (2).将重复的字符替换为一个字符

		//将重复的字符替换成一个字符
		str = "qweqwdsdddsasdasqqqqqdsdsaqfdsddddd";
		//定义正则表达式,为了后面替换的时候能知道替换的是重复的哪一个字母这里对此正则表达式用括号分组,这里的(.)为第一个组
		rex = "(.)\\1+";
		//定义要替换的字符串,$1表示上一个正则表达式中的第一个组
		newstr = "$1";
		test(str, rex, newstr);
		
	}

  

其中test方法为:

/**
	 * 用正则表达式替换字符串中的字符
	 * @param str 要处理的字符串
	 * @param rex 进行处理的正则表达式
	 * @param newstr 要用来替换的字符串
	 */
	public static void test(String str,String rex,String newstr){
		//字符串直接替换可以用replace,如果是正则表达式替换就要用replaceAll
		String str2 = str.replaceAll(rex, newstr);
		System.out.println(str2);
	}

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics