【java基础】正则表达式

1.正则表达式的概念

2.应用

单个字符的匹配(字母、数字、字符、字符串…

public static void main(String[] args) {
    
    
//		String str="a32";
//				String regex="[a-z][0-9][0-9]";//中括号中间不能有空格 [a-zA-Z]表示不限大小写
//				System.out.println(str.matches(regex));
	  String a="f12";	
	  String regex="[fab][0-9][0-9]";//[]第一项包含f字母暨为true
	  System.out.println(a.matches(regex));
	}
/**
 * 判断字符串是否以数字或字母开头等等..
 * @param args
 */
public static void main(String[] args) {
    
    
	String str="e$@";
	String regex="[^0-9a-z][0-9][0-9]";//[^0-9a-z] 表示第一项不是数字或小写字母
	System.out.println(str.matches(regex));
}
	public static void main(String[] args) {
    
    
		String gender = "保密";
		String regex = "[男]| [女]|(保密)";// 或| 字符串需要加小括号
		System.out.println(gender.matches(regex));

	}

多个字符的匹配(匹配0、1、n次…/号码/身份证匹配…

public static void main(String[] args) {
    
    
	String str="123456";
	String regex="[0-9]{6}";//{6} 表示匹配n次
	System.out.println(str.matches(regex));
	

	String regex4="[0-9]{6,}";//{6,}表示至少匹配6次
	String regex6="[0-9]+";//+表示至少匹配1次
	String regex9="[0-9]*";//*表示匹配0次或者多次	
	String regex10="[0-9]?";//*表示匹配0次或者1次
	
	String regex5="[0-9]{6,12}";//{6,12}表示匹配6-12次
	String regex7="\\d+";// \\d表示[0-9]
	
	
	
	//匹配电话
	String phonenum="1500000000";
	String regex2="[1][0-9]{10}";
	System.out.println(phonenum.matches(regex2));
	
	//匹配身份证
	String identityNum="350000000000000000";
	String regex3="[1-9][0-9]{16}[0-9X]";
	System.out.println(identityNum.matches(regex3));
}

找出字符串中的中文并输出

/**
 * 找出字符串中的中文并输出
 * 正则+api替换
 * @author wdy
 *
 */
public class String14 {
    
    
public static void main(String[] args) {
    
    
	String str="djjab点击dhsfJD3E3N的2JBJJ大家B341";
	String regex="[^\u4e00-\u9fa5]+";//找出字符串中不是中文的
	
	String s=str.replaceAll(regex, "");//replaceALL 将不是中文的替换为空
	System.out.println(s);
}
}

统计字符串中指定字符(apple)出现次数

/**
 * 统计字符串中指定字符串(apple)出现的次数
 * @param wdy
 */

	 public static void main(String[] args) {
    
    
	 String a="there are one apple,two apples,three apples,many apples,how many apples i have?";
	 f(a);
	 System.out.println("苹果"+b);
	 
/*
 * 方法一:运用正则表达式替换
 */
//     String s=a.replaceAll("apple", "#");
//     System.out.println(s.replaceAll("[^#]", ""));
	
	
/*
 * 方法二.利用循环
 */
//	int index=0;
//	int num=0;
//	while(true) {
    
    
//		index=a.indexOf("apple",index);
//		if(index==-1) {
    
    
//			break;
//		}else {
    
    
//			num++;
//			index+="apple".length();
//		}
//	}
	
	 
/*
 * 方法3.运用String api-split 字符串拆分装换为单个字符数组
*/
//   int cout=0;	
//	 String[]ss=a.split("[ ,]");
//	 
//	 for(String sx:ss) {
    
    
//		 System.out.println(sx);
//		 if(sx.contains("apple")) {
    
    
//		 cout++; 
//		 }
//	 }System.out.println("苹果有"+cout);
//   }
	
	 
/*
* 方法4 递归
*/
//	
	 static int b=0;
	 public static void f(String a) {
    
    
		 int index =a.indexOf("apple");
		 if(index==-1) {
    
    
			 return;
		 }
		 b++;
		 f(a.substring(index+"apple".length()));
		 
	 }
	

猜你喜欢

转载自blog.csdn.net/wdy00000/article/details/121703153
今日推荐