正则表达式用于匹配各种类型的字符和模式。以下是一些常见的正则表达式模式及其含义:
一.字符类
-
\\d:匹配任何数字字符,相当于[0-9]。 -
\\D:匹配任何非数字字符,相当于[^0-9]。 -
\\w:匹配任何字母数字字符(包括下划线),相当于[a-zA-Z0-9_]。 -
\\W:匹配任何非字母数字字符,相当于[^a-zA-Z0-9_]。 -
\\s:匹配任何空白字符(空格、制表符、换页符等),相当于[ \t\n\x0B\f\r]。 -
\\S:匹配任何非空白字符,相当于[^ \t\n\x0B\f\r]。
二.数量词
-
*:匹配前面的模式零次或多次。 -
+:匹配前面的模式一次或多次。 -
?:匹配前面的模式零次或一次。 -
{n}:匹配前面的模式恰好 n 次。 -
{n,}:匹配前面的模式至少 n 次。 -
{n,m}:匹配前面的模式至少 n 次,至多 m 次。
三.边界匹配
-
^:匹配字符串的开头。 -
$:匹配字符串的结尾。 -
\\b:匹配单词边界。 -
\\B:匹配非单词边界。
四.分组和引用
-
(...):捕获组,匹配括号内的表达式,并记住匹配的文本。 -
(?:...):非捕获组,匹配括号内的表达式,但不记住匹配的文本。 -
\\1, \\2, ...:反向引用,匹配之前捕获的组。
五.示例用法
-
匹配一个或多个字母数字字符
String str = "abc123"; boolean matches = str.matches("\\w+"); System.out.println(matches); // 输出 true -
匹配一个电话号码格式(如 123-456-7890)
String phoneNumber = "123-456-7890"; boolean matches = phoneNumber.matches("\\d{3}-\\d{3}-\\d{4}"); System.out.println(matches); // 输出 true -
替换连续的多个空白字符为一个空格
String str = "a b\tc d"; String result = str.replaceAll("\\s+", " "); System.out.println(result); // 输出 "a b c d" -
匹配一个邮箱地址
String email = "example@test.com"; boolean matches = email.matches("\\w+@\\w+\\.\\w+"); System.out.println(matches); // 输出 true -
提取每个单词
String str = "Hello, world!"; String[] words = str.split("\\W+"); for (String word : words) { System.out.println(word); // 输出 "Hello" 和 "world" }