Java: String 类对正则的支持

java.long.String 中的对正则的支持方法

进行字符串验证, 匹配某个正则

public boolean matches(String regex)

根据正则替换全部

public String replaceAll(String regex,   String replacement)

根据正则替换首个

public String replaceFirst(String regex,
                           String replacement)

根据正则拆分

public String[] split(String regex)

根据正则拆分成指定的个数

public String[] split(String regex,
                      int limit)

案例, 找出字符串中的字母

package com.cwq.beyond;

public class test22 {
	public static void main(String[] args) {
		String str = "@#@#fdsafSJHFK&*(IDHFK^F(#@HJHKJsdfsafw213214KJHdsf*^#Jkh324jk2#@";
		String regex = "[^a-zA-Z]";
		System.out.println(str.replaceAll(regex, ""));
		
	}

}

在这里插入图片描述

案例: 字符串拆分(按数字拆分)

package com.cwq.beyond;

public class test22 {
	public static void main(String[] args) {
		String str = "aaaa980943bbbUUER89wer89Jjls";
		String regex = "\\d+";  // 正则[0-9]
		String data[] = str.split(regex);
		for (int i = 0; i < data.length; i++) {
			System.out.println(data[i]);
		}
		
	}

}

在这里插入图片描述

案例: 验证字符串是否是数字(包括整数和小数),如果是要变成Double型

package com.cwq.beyond;

public class test22 {
	public static void main(String[] args) {
		String str = "11011";
		String regex = "\\d+(\\.\\d+)?";  // (\\.\\d+)? 量词, 0 次或者 一次, ()表示一个整体
		
		if (str.matches(regex)) {
			Double data = Double.parseDouble(str);
			System.out.println(data);
		}
		
	}

}

在这里插入图片描述

案例: 判断一个字符串是否是日期类型, 是则转化成Date型

package com.cwq.beyond;

import java.text.SimpleDateFormat;

public class test22 {
	public static void main(String[] args) throws Exception{
		String str = "2020-10-12 14:45:12";
		String regex = "\\d{4}-\\d{2}-\\d{2}";  
		
		if (str.matches(regex)) {
			System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse(str));
		}else if (str.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
			System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(str));
		}							
	}

}

在这里插入图片描述

案例: 判断给定的电话号码格式是否正确

package com.cwq.beyond;

import java.text.SimpleDateFormat;

public class test22 {
	public static void main(String[] args) throws Exception{
		
		/*
		 * 电话格式1 : 12345678
		 * 电话格式2 : 01012345678
		 * 电话格式3 : (010)-12345678
		 */
		String str[] = {"12345678","01012345678","(010)-12345678"};
		String regex = "(\\()?(\\d{3,4})?(\\)-)?\\d{7,8}";    // 或者: (\\(\\d{3,4}\\)-|(\\d{3,4}))?\\d{7,8}
		for (int i = 0; i < str.length; i++) {
			if (str[i].matches(regex)) {
				System.out.println("格式正确");
			}else {
				System.out.println("格式错误");
			}
		}		
	}

}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_大木_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值