Java基础---认识正则表达式

认识正则表达式

正则表达式概述

1、正则表达式:本质上就是一个字符串,这个字符串可以表达一类具有某种规则的字符串。
2、字符类型:表示单个的字符,使用的符号是中括号[]
只要使用了方括号无论里面写了多少内容,都表示的是单个字符
3、方括号的表示形式:
[abc]:a或者b或者c的一个字符
[^abc]:除了a,b,c以外的任何的单个字符
[a-zA-Z]: a-z 和A-Z中的一个字符
4、判断某个字符串和正则表达式的规则相匹配的,要用String类中的match(String regex)

	public static void main(String[] args) {
		String regex = "[a-zA-Z]";
		System.out.println("a".matches(regex));//true
		System.out.println("ab".matches(regex));//false
		System.out.println("m".matches(regex));//true
		System.out.println("Q".matches(regex));//true
		System.out.println("".matches(regex));//false
	}

	private static void main(String[] args) {
		String regex = "[^abc]";
		System.out.println("a".matches(regex));//false
		System.out.println("ab".matches(regex));//false
		System.out.println("m".matches(regex));//true
		System.out.println(" ".matches(regex));//true
		System.out.println("".matches(regex));//false
	}

预定义字符类

. 表示任意的字符 \.表示的就是.
\d 表示的数字字符
\D 表示的是非数字字符
\s 表示的是空格字符
\S 表示的非空格字符
\w 表示的[a-zA-Z0-9]
\W 表示的是除了\w的外的所有字符

数量词

模糊的数量词
X? 表示的是X这个字符出现0次或者1次
X+ 表示的是X这个字符出现1次或者多次
X* 表示的是X这个字符出现0次,1次,或者多次
精确的数量词
X{n} 表示X这个字符恰好出现n次
X{n,} 表示的X这个字符,至少出现n次
X{n,m}表示的是X这个字符,至少出现n次,最多出现m次

字符串中和正则表达式有关的三个方法

1、boolean match(String regex),告知此字符串是否匹配给定的正则表达式。
2、String[] split(String regex) 使用指定的正则表达式切割字符串
3、replaceAll(String regex,String replacement)使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串

package com.DaYu;

public class Demo12 {
	public static void main(String[] args) {
             
			 String string = "a6b7cd8sa9fdasf";
			 String replaceAll = string.replaceAll("\\d+", "\\$");
			 System.out.println(replaceAll);  //a$b$cd$sa$fdasf
			 
			 String string1 = "a6b7cd8sa9fdasf";
			 String[] split = string1.split("\\d+");
			 for (int i = 0; i < split.length; i++) {
			     System.out.println(split[i]);
			 }
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41401295/article/details/106556002