我是靠谱客的博主 激情大船,这篇文章主要介绍JavaSE基础之正则表达式,现在分享给大家,希望可以做个参考。

符号描述
转义符
?匹配前面的表达式零次或一次        等价于{0,1}
*匹配前面表达式任意次                等价于{0,}
+匹配前面表达式一次或多次        等价于{1,}
.匹配除了"rn"以外的任意单个字符
[^xyz]匹配不包含的任意一个字符
d匹配一个数字字符                等价于[0-9]        D:匹配一个非数字
w匹配包括下划线的任何当个字符        类似[A-Za-z0-9_]
s

匹配不可见字符,空格、制表符、换页符等,等价于[ fnrtv]

1.Pattern类:用于创建一个正则表达式

复制代码
1
2
3
4
5
6
7
8
9
String string = "1.2.3"; // 创建一个正则表达式 Pattern pattern = Pattern.compile("\."); // 以.分割返回字符串数组 String[] str = pattern.split(string); // 把数组转化为集合 List<String> strList = Arrays.asList(str); System.out.println(strList);

2.Matcher类:用于匹配

        常用方法:

matches()对字符串进行全词匹配,只有整个字符串都匹配成功才会返回true
lookingAt()从前往后匹配,
find()任意位置进行匹配        注:可以与group()一起使用,用于取出数据
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
String regex = "\d{11}"; String string = "a151334500122"; // 创建一个正则表达式 Pattern pattern = Pattern.compile(regex); // 匹配器 Matcher matcher = pattern.matcher(string); // matches():全词匹配 System.out.println(matcher.matches());// false /** * find与matches不能连用,需要重新创建匹配器 */ matcher = pattern.matcher(string); // find():任意位置 System.out.println(matcher.find());// true matcher = pattern.matcher(string); // lookingAt():从前到后匹配 System.out.println(matcher.lookingAt());// false:因为第一字符为a,所以直接返回false /** * find和group一起使用,可以取出数据 */ String regexTel = "(我的电话号码是)(\d{11})"; String tel = "aaaaa我的电话号码是15133450012"; pattern = Pattern.compile(regexTel); matcher = pattern.matcher(tel); if (matcher.find()) { // group():参数可以为int型,且保证正则表达式有()划分 System.out.println(matcher.group()); }

最后

以上就是激情大船最近收集整理的关于JavaSE基础之正则表达式的全部内容,更多相关JavaSE基础之正则表达式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部