正则表达式:预定义字符类
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