正则表达式Pattern类和Matcher类

正则表达式:本质是一个字符串,用来定义匹配规则的。

字符x    代表的是字符x

\\          代表的是反斜线\

\t          制表符

\n         换行符

\r          回车符

[abc]     代表的是字符a、b或c

[^abc]   代表的是除a b c 以外的任何字符

[a-zA-Z] 代表的是a到z或A到Z

[0-9]      代表的是0-9数字

[a-zA-Z_0-9] 代表的是字母或数字或下划线

.              代表任何字符

\d           代表0-9数字

\w           代表字母数字下划线

x?            代表的是x出现一次或一次都没有

x*                                  零次或多次

x+                                 一次或多次

x{n}                               恰好n次

x{n,}                              至少n次

x{n,m}                           至少n次但不超过m次


Pattern类:作用是编译正则表达式后创建一个匹配模式

方法:

Pattern compile(String regex) 由于Pattern类的构造函数是私有的,不可以直接创建,所以通过静态方法compile(String regex)方法来创建,将给定的正则表达式编译并赋予给Pattern类


Matcher matcher(String str) 对指定的字符串创建一个Matcher对象

boolean matches()  对输入的字符串进行匹配检测,也就是整个字符串完全匹配才返回真值。


一个小Demo

public class PatternDemo {
public static void main(String[] args) {
String pattern = "[?|*]";
Pattern p = Pattern.compile(pattern);
System.out.println(p.pattern());
String str ="*";
Matcher m = p.matcher(str);
System.out.println(m.matches());
}

}


字符串类中涉及正则表达式的常用方法

boolean matches(String regex)  匹配成功返回true

String[]  split(String regex)          使用规则将字符串分割

String replaceAll(String regex,String str)  按照规则替换字符串

public class RegexDemo {
public static void main(String[] args) {

//字符串中涉及正则表达式的方法
String regex = "a*b";
String s = "aaab";
boolean flag = s.matches(regex);
System.out.println(flag);

String s1 ="ab.ba.baab";
String regex1 ="\\.";
String[] splitStr = s1.split(regex1);
for(int i=0;i<splitStr.length;i++){
System.out.println("第"+(i+1)+"个是:"+splitStr[i]);
}

String s2 = s1.replaceAll(regex1, "cc");
System.out.println(s2);

}

}

猜你喜欢

转载自blog.csdn.net/yy23yy80/article/details/80756885