1. 背景
需要把接收的字符串文本里面的特殊字符给转义,例如对   ,<br>,<br />等进行处理
2. 方案
使用正则匹配进行数据替换
/**
*
* 配置   以及 两种方式的空格
*
*
*
*/
@Test
public void match1(){
String regex_Space = "\\ [\\;]{0,1}";
String str = "<br>a <br /> and and and";
System.out.println(str.replace(" ", " "));
System.out.println(str.replaceAll(regex_Space, " "));
// ps:曾一度认为replace是首个匹配的 字符 或 字符串 替换,replaceAll是目标字符串中全部匹配的字符 或 字符串替换。
// 这种观点是错误的
}
/**
*
*
* 忽略br的大小写 来进行匹配
*
*
*/
@Test
public void match2(){
String regex = "\\<(?i)br\\s*[\\/]{0,1}\\>";
String str = "<Br />bbbt<bR >wwisdk<br>dsada<BR />QQQ";
System.out.println (str.replaceAll(regex, "\n"));
}
执行结果见下图:
三.未完更多
后续遇到更多形式的正则匹配,继续补充