Java学习日志14.3 (第一阶段基础)

2018.10.23 天气阴
黑马程序员养成记录第3天

5_常见对象(正则表达式的分割功能)

新知识梗概:
正则表达式的分割功能
String类的功能:public String[] split(String regex)

根据匹配给定的正则表达式来拆分此字符串
返回类型:String[ ]

代码练习
package com.heima.Regex;

public class demo5_Regex {  
public static void main(String[] args) {
	String s = " aaa bbb ccc ddd";
	String []arr1 = s.split(" ");		//空格作为正则表达式
	for (int i = 0; i < arr1.length; i++) {
		System.out.println(arr1[i]); 
	}
	System.out.println("-------");
	String s2 = "aaa.bbb.ccc.ddd";	//"."作为正则表达式
	String regex = "\\.";		//“\\”是转义符
	 String []arr2 = s2.split(regex);
	for (int i = 0; i < arr2.length; i++) {
	      	System.out.print(arr2[i]);
	      	System.out.println();
			}	
}
}

程序结果:

aaa
bbb
ccc
ddd
-------
aaa
bbb
ccc
ddd

14.07_常见对象(常见对象(正则表达式的替换功能))

知识:正则表达式的替换功能
实现方法:String类的功能:public String replaceAll(String regex,String replacement) 将regex匹配的字符全部替换为replacement

代码练习;

package com.heima.Regex;

public class demo8_regex {
	public static void main(String[] args) {
		String  s1 = "wo321yao4cheng6132wei21hei233ma65644chengx2vyuan";	//数字字母混合字符串
		String regex = "\\d";	// "\\d" 代表任意字符串
		String s2 = s1.replaceAll(regex, "");	//将数字字符全部替换为空字符	
		System.out.println(s2);
	}
}

程序结果:
woyaochengweiheimachengxvyuan

17.08_常见对象(正则表达式的分组功能)

*知识:
捕获组可以通过从左到右计算其开括号来编号。例如,在表达式 ((A)(B©)) 中,存在四个这样的组:
*
1 ((A)(B©))
2 (A)
3 (B©)
4 ©
组零始终代表整个表达式。

public class demo9_regex {
	public static void main(String[] args) {
		//叠词 快快乐乐,高高兴兴
		String regex = "(.)\\1(.)\\2";	//(.)\\1代表第一组又出现一次,(.)\\2代表第二组又出现一次
		System.out.println("快快乐乐".matches(regex));
		System.out.println("快快快乐".matches(regex));
		System.out.println("高高兴兴".matches(regex));
		System.out.println("----------");
		//叠词  快乐快乐,高兴高兴
		String regex2 = "(..)\\1";	// 表示任意两个字符成一组,第一组再出现一次
		System.out.println("快快乐乐".matches(regex2));
		System.out.println("快乐快乐".matches(regex2));
		System.out.println("高高兴兴".matches(regex2));
	}
}

程序结果:

true
false
true

false
true
false

猜你喜欢

转载自blog.csdn.net/binge_kong/article/details/83301998