Java正则表达式 自动特殊字符进行转义相关的包 代码段例子
Java中用于正则表达式转义的包是java.util.regex。
下面是一个例子:
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String text = "This is a test string with special characters: $, ^, (, ), {, }, [, ], \\, |, ?, *, +, .";
String pattern = "\\$|\\^|\\(|\\)|\\{|\\}|\\[|\\]|\\\\|\\||\\?|\\*|\\+|\\."; // 需要转义的特殊字符前面加上反斜杠 \
Pattern p = Pattern.compile(pattern);
String[] tokens = p.split(text);
for (String token : tokens) {
System.out.println(token);
}
}
}
输出:
This is a test string with special characters:
,
,
,
,
,
,
,
,
,
,
,
,
,
,
.
``
原文地址: https://www.cveoy.top/t/topic/d9AZ 著作权归作者所有。请勿转载和采集!