正则表达式
1、是什么
一串具体特殊作用的字符串,java引进了java.util.regex包用以支持正则表达式
2、怎么用
-
分为只使用Pattern类与两个类联合使用:Pattern、Matcher
Pattern:
1、boolean Pattern.matches(String regex,CharSequence input)
regex:正则表达式 ,input:要匹配的字符串。
String str="12dr 32 d2d"; System.out.println(Pattern.matches("\\d+", str)); // 一定要全部是数字才行返回true
2、String[] Pattern.split(CharSequence input)
分割字符串
Pattern p=Pattern.compile("\\d+"); String[] str=p.split("a1b1c1"); 结果: str[0]="a" str[1]="b" str[2]="c"
2.Pattern、Matcher联合使用可以多次匹配和对正则表达式的分组支持
1.Matcher.matches():看是否全部为正则表达式的类型,返回布尔值
Pattern compile = Pattern.compile("\\d+");
Matcher matcher = compile.matcher("22bb11");
System.out.println(matcher.matches());// 返回false,因为"22bb11"不全部是数字
结果:
false
2、lookingAt():只看第一个匹配到的是不是正则表达式要的。
Pattern compile = Pattern.compile("\\d+");
Matcher matcher = compile.matcher("22bb11");
System.out.println(matcher.lookingAt());// 返回true,因为"22bb11"开头是数字
结果:
true
3、**find()**对字符串进行匹配,匹配到的字符串可以在任何位置.
Pattern compile = Pattern.compile("\\d+");
Matcher matcher = compile.matcher("22bb11");
System.out.println(matcher.find());// 返回true,因为"22bb11"中有数字数字
当使用matches(),lookingAt(),find()执行匹配操作后,就可以利用以上三个方法得到更详细的信息.
5.Mathcer.start()/ Matcher.end()/ Matcher.group()
start()返回匹配到的子字符串在字符串中的索引位置.
end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.
group()返回匹配到的子字符串
Java代码示例:
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher("aaa2223bb");
m.find();//匹配2223 // 必写,调用此方法后才能调用后面的三个方法
m.start();//返回3
m.end();//返回7,返回的是2223后的索引号
m.group();//返回2223
还有正则表达式还包括捕获组的操作
即:
"((\\d+)(.*))" // 一个括号中包含两个括号,每个括号中代表一种正则表达式,我们可以利用组的操作去获取不同数据类型的数据。
在 java 中
start(),end(),group()均有一个重载方法它们是**start(int i),end(int i),group(int i)**专用于分组操作,Mathcer类还有一个groupCount()用于返回有多少组.
例:
Pattern p=Pattern.compile("([a-z]+)(\\d+)");
Matcher m=p.matcher("aaa2223bb");
m.find(); //匹配aaa2223
m.groupCount(); //返回2,因为有2组
m.start(1); //返回0 返回第一组匹配到的子字符串在字符串中的索引号
m.start(2); //返回3
m.end(1); //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置.
m.end(2); //返回7
m.group(1); //返回aaa,返回第一组匹配到的子字符串
m.group(2); //返回2223,返回第二组匹配到的子字符串
3、使用
注意:只有当匹配操作成功,才可以使用start(),end(),group()三个方法,否则会抛出java.lang.IllegalStateException,也就是当matches(),lookingAt(),find()其中任意一个方法返回true时,才可以使用.
1、将一串文本中的数字全部取出来,如:
aaa11 azs 23 ff3g5knj64b
Pattern compile = Pattern.compile("\\d+");
Matcher matcher1 = compile.matcher("aaa11 azs 23 ff3g5knj64b");
while (matcher1.find()){ // 判断文本中是否有数字
System.out.println(matcher1.group()); // 有就输出
}
结果:
11
23
3
5
64
Process finished with exit code 0
2、判断某个数字是不是在一个数字集合中。
Pattern compile = Pattern.compile("1|3|5|7|8|10|12"); // 集合中设置每月天数为31的
Matcher matcher = compile.matcher("7"); // 7月份
if (matcher.find()){ // 判断月份为7时,在不在上面的集合中
System.out.println(true);
}
正则表达式的其他语法
链接:https://www.runoob.com/java/java-regular-expressions.html