62,614
社区成员
发帖
与我相关
我的任务
分享
public class Test {
public static void main(String[] args) {
String str = "hi'dmh 100% a_b= 100\\200";
System.out.println("Old: " + str);
String regex = "(?=['%_\\\\])";
str = str.replaceAll(regex, "\\\\");
System.out.println("New: " + str);
}
}
输出结果:
Old: hi'dmh 100% a_b= 100\200
New: hi\'dmh 100\% a\_b= 100\\200
String str = "hi'dmh 100% a_b= 100\\200";
String regex = "\'|%|_|\\\\";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer("");
while(m.find())
{
int start = m.start();
int end = m.end();
String temp = str.substring(start, end);
if(temp.equals("\'") || temp.equals("\\"))
{
temp = "\\" + temp;
}
m.appendReplacement(sb, "\\\\" + temp);
}
m.appendTail(sb);
//最终结果
String ret = sb.toString();
System.out.println(ret);