正则表达式:预定义字符类,字符型的使用示例

本文深入探讨了正则表达式中的预定义字符类及其用法,通过具体示例展示了如何在正则表达式中有效地使用字符型。无论你是Java开发者还是对正则表达式感兴趣的程序员,都将从中受益。
摘要由CSDN通过智能技术生成

正则表达式:预定义字符类

package com.regex;

import org.junit.Test;

/**
 * 正则表达式:预定义字符类
 * . :匹配任何字符
 * \d :表示匹配一位数字,它等价于[0-9]
 * \D :表示匹配除数字以外的字符,等价于[^0-9]
 * \s :表示匹配一个空白字符
 * \S :表示匹配一个非空白字符,等价于[^\s]
 * \w :表示匹配字母,数字和下划线,等价于[a-zA-Z_0-9]
 * \W :匹配除字母、数字和下划线以外的任意字符,等价于[^\w]和[^0-9a-zA-Z_]
 */
public class RegexTest03 {
   
	//. 任何字符(与行结束符可能匹配也可能不匹配)
	@Test
	public void test01() {
   
		//String regex = ".";
		String regex = "\\."; // \. 此方式表示这个是一个普通.
		System.out.println("  ".matches(regex)); // false
		System.out.println(".".matches(regex));//true
		System.out.println("\r".matches(regex)); // false
	}
	
	//	\d 数字:[0-9],表示匹配一位数字,它等价于[0-9]
	@Test
	public void test02() {
   
		//String regex = "\\d";
		String regex = "[0-9]";
		System.out.println("a".matches(regex));
		System.out.println("z".matches(regex));
		System.out.println("M".matches(regex));
		System.out.println("X".matches(regex));
		System.out.println("0".matches(regex)); // true
		System.out.println("9".matches(regex)); // true
		System.out.println("10".matches(regex));
	}
	
	//	\D 非数字: [^0-9],表示匹配除数字以外的字符,等价于[^0-9]
	@Test
	public void test03() {
   
		//String regex = "\\D";
		String regex = "[^0-9]";
		System.out.println("a".matches(regex));
		System.out.println("z".matches(regex));
		System.out.println("M".matches(regex));
		System.out.println("X".matches(regex));
		System.out.println("0".matches(regex)); // false
		System.out.println("9".matches(regex)); // false
		System.out.println("10".matches(regex)); // false
	}
	
	//	\s 空白字符:[ \t\n\x0B\f\r],表示匹配一个空格字符
	@Test
	public void test04() {
   
		String regex = "\\s";
		System.out.pri
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值