Java正则表达式的使用

mac2024-03-17  39

目录

一、正则匹配1.1、精确匹配1.2、模糊匹配1.2.1 单次匹配1.2.2 重复匹配1.2.3 复杂匹配 二、常见操作2.1、匹配(matches)2.2、分割(split)2.3、替换(replaceAll)2.4、搜索并获取

一、正则匹配

正则表达式只用于操作字符串数据,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 重复匹配

序号正则表达式匹配说明1X*X, 零 次 或 多 次 \color{blue}{零次或多次} 2X+X, 一 次 或 多 次 \color{blue}{一次或多次} 3X?X, 一 次 或 一 次 也 没 有 \color{blue}{一次或一次也没有} 4X{n}X, 恰 好 n 次 \color{blue}{恰好n次} n5X{n,}X, 至 少 n 次 \color{blue}{至少n次} n6X{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} abc4[^abc]任何字符, 除 了 a 、 b 或 c \color{green}{除了a、b或c} abc5[a-zA-Z] a 到 z 或 A 到 Z \color{green}{a到z或A到Z} azAZ6ab|c|d a b 、 c 或 d \color{green}{ab、c或d} abcd7(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
最新回复(0)