Java 正则表达式可使用 \p{Punct} 字符类匹配标点符号,具体语法如下:\p{Punct}:匹配任何标点符号字符
Java 正则表达式匹配标点符号
在 Java 中使用正则表达式匹配标点符号非常简单。可以使用 \p 字符类来识别标点符号。
\p{Punct}示例:
String text = "This sentence contains various punctuation marks.,!?"
// 查找并打印文本中的所有标点符号
Pattern pattern = Pattern.compile("\\p{Punct}");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}输出:
. , ! ?
其他示例:
\p{Punct}.
\p{Punct},
\p{Punct}!
\p{Punct}?
注意:
\p{Punct} 字符类不包括空格。\\s 字符类。[\\p{Punct}\\s] 将匹配标点符号和空格。