Java正则篇-23-预定义字符类

       前面一篇了解了字符类,这篇来学习预定义字符类。没什么好说的,先每个字符类都写一个正则表达式来测试下,通过举例一些正向和反向的例子来练习。反正一开始,用得少记不住每个字符的含义,后面用多了,自然就会写正则表达式。

 

1. 在API文档关于预定义字符类


上面同样是用来匹配单个字符的

 

2. 代码练习

 

针对没个字符类写一个方法来测试

package regex;

public class Demo1_Regex {

	public static void main(String[] args) {
		//demo1();
		//demo2();
		//demo3();
		//demo4();
		//demo5();
		//demo6();
		demo7();
	}

	public static void demo7() {
		String regex = "\\W";  // 表示非单词字符,就是标点符号
		System.out.println("\n".matches(regex)); 
		System.out.println("&".matches(regex));
		System.out.println("#".matches(regex));
		System.out.println("a".matches(regex));
		System.out.println("9".matches(regex));
	}

	public static void demo6() {
		String regex = "\\w";  // 表示单词字符:[a-zA-Z_0-9]
		System.out.println("\n".matches(regex)); 
		System.out.println("a".matches(regex));
		System.out.println("H".matches(regex));
		System.out.println("i".matches(regex));
		System.out.println("Z".matches(regex));
		System.out.println("9".matches(regex));
	}

	public static void demo5() {
		String regex = "\\S";  // 表示非空白字符
		System.out.println("\t".matches(regex)); 
		System.out.println("a".matches(regex));
	}

	public static void demo4() {
		String regex = "\\s";  // 表示空白字符
		System.out.println("\t".matches(regex)); // 制表符
		System.out.println("\f".matches(regex));
		System.out.println("\n".matches(regex)); //回车并换行
		System.out.println("\r".matches(regex));  // 回车符
	}

	public static void demo3() {
		String regex = "\\D";  // 表示非数字,注意单个\表示转译字符
		System.out.println("a".matches(regex));
		System.out.println("你".matches(regex));
		System.out.println("&".matches(regex));
		System.out.println("7".matches(regex));
	}

	public static void demo2() {
		String regex = "\\d";  // 表示数字0-9,注意单个\表示转译字符,所以这里需要\\d
		System.out.println("0".matches(regex));
		System.out.println("9".matches(regex));
		System.out.println("10".matches(regex));
	}

	public static void demo1() {
		String regex = "."; 
		System.out.println("a".matches(regex));
		System.out.println("a".matches(regex));
		System.out.println("ab".matches(regex));
		
		String regex2 = ".."; 
		System.out.println("ab".matches(regex2));
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值