Java正则表达式的使用
发布日期:2021-11-04 11:54:27 浏览次数:9 分类:技术文章

本文共 2504 字,大约阅读时间需要 8 分钟。

目录

一、正则匹配

正则表达式只用于操作字符串数据,java标准库的正则表达式解析引擎位于java.util.regex包中。

1.1、精确匹配

正则表达式abc,它只能精确匹配字符串"abc",无法匹配到"abcd"、“ABC”、"aBc"等其它字符串。

若正则表达式中含有特殊字符,必须要用\来转义;由于\也是Java的转义字符之一,所以正则表达式\\,它匹配单个反斜杠。
精确匹配实际上等同于String.equals(),实际上用处并不大。

1.2、模糊匹配

1.2.1 单次匹配

序号 正则表达式 匹配说明
1 . 任 何 一 个 \color{red}{任何一个} 字符
2 \d 任 何 一 个 \color{red}{任何一个} 数字
3 \w 任 何 一 个 \color{red}{任何一个} 单词字符(字母、数字、下划线)
4 \s 任 何 一 个 \color{red}{任何一个} 空白字符(空格符、水平制表符、垂直制表符、换行符、回车符、换页符)
5 \D 任 何 一 个 \color{red}{任何一个} 数字
6 \W 任 何 一 个 \color{red}{任何一个} 单词字符
7 \S 任 何 一 个 \color{red}{任何一个} 空白字符

1.2.2 重复匹配

序号 正则表达式 匹配说明
1 X* X, 零 次 或 多 次 \color{blue}{零次或多次}
2 X+ X, 一 次 或 多 次 \color{blue}{一次或多次}
3 X? X, 一 次 或 一 次 也 没 有 \color{blue}{一次或一次也没有}
4 X{n} X, 恰 好 n 次 \color{blue}{恰好n次} n
5 X{n,} X, 至 少 n 次 \color{blue}{至少n次} n
6 X{n,m} X, 至 少 n 次 , 但 是 不 超 过 m 次 \color{blue}{至少n次,但是不超过m次} nm

1.2.3 复杂匹配

序号 正则表达式 匹配说明
1 ^ 行 的 开 头 \color{green}{行的开头}
2 $ 行 的 结 尾 \color{green}{行的结尾}
3 [abc] a 、 b 或 c \color{green}{a、b或c} abc
4 [^abc] 任何字符, 除 了 a 、 b 或 c \color{green}{除了a、b或c} abc
5 [a-zA-Z] a 到 z 或 A 到 Z \color{green}{a到z或A到Z} azAZ
6 ab|c|d a b 、 c 或 d \color{green}{ab、c或d} abcd
7 (a)c(e) 分 组 匹 配 \color{green}{分组匹配}

二、常见操作

2.1、匹配(matches)

String input = "15812345678";String regex = "1[358]\\d{9}";boolean b = input.matches(regex); System.out.println(b);// true
// 对于重复的匹配,建议采用如下方式Pattern p = Pattern.compile(regex);Matcher m = p.matcher(input);boolean b = m.matches();// 等效于 boolean b = Pattern.matches(regex, input);

2.2、分割(split)

String input = "BobttttAlicemmmmmTom";String regex = "(.)\\1+"; // 反向引用匹配到()捕获组String[] arr = input.split(regex); System.out.println(Arrays.toString(arr));// [Bob, Alice, Tom]
Pattern p = Pattern.compile(regex);String[] arr = p.split(input);System.out.println(Arrays.toString(arr));// [Bob, Alice, Tom]

2.3、替换(replaceAll)

String input = "15812345678";String regex = "(\\d{3})(\\d{4})(\\d{4})";String s = input.replaceAll(regex, "$1****$3"); // 反向引用匹配到的字符串System.out.println(s);// 158****56789
Pattern p = Pattern.compile(regex);Matcher m = p.matcher(input);if (m.matches()){
String s = m.replaceAll("$1****$3"); System.out.println(s); // 158****56789}

2.4、搜索并获取

String input = "Moderation is for cowards.";String regex = "\\b\\w*o\\w*\\b";Pattern p = Pattern.compile(regex);Matcher m = p.matcher(input);while (m.find()){
String s = input.substring(m.start(), m.end()); System.out.println(s);}// Moderation// for// cowards

转载地址:https://blog.csdn.net/WXS_0218/article/details/102832269 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:openssh
下一篇:新旧版本Java时间、日期API转化

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年03月23日 00时15分51秒