java中如何替换第二个被匹配到的字符串
java中怎么替换第二个被匹配到的字符串?
比如
str="sssegegegsssgege";
想把第二个匹配到的sss给替换掉,替换成hello
结果就是
str="sssegegeghellogege";
应该怎么弄?
------解决方案--------------------
------解决方案--------------------
正则表达式果然强大。当然如果没有接触过的话,下面这种方法可能更容易理解。
------解决方案--------------------
话说因为你的img里面有需要转义的字符
\Q \E之间的部分,代表里面的内容全是普通文本的引用,不要把它当作正则看待
比如
str="sssegegegsssgege";
想把第二个匹配到的sss给替换掉,替换成hello
结果就是
str="sssegegeghellogege";
应该怎么弄?
------解决方案--------------------
String str="sssegegegsssgege";
str=str.replaceAll("(sss)(.*?)(\\1)(.*?)", "$1$2hello$4");
System.out.println(str);
------解决方案--------------------
正则表达式果然强大。当然如果没有接触过的话,下面这种方法可能更容易理解。
/**
* 替换第二个匹配的目标子串
* @param str 源字符串。
* @param target 需要替换的目标子串。
* @param replacement 需要替换成的字符串。
* @return 将源字符串中出现的第二个target换成replacement后的字符串。
* @throws NullPointerException 当任一参数为空时。
* @throws Exception 找不到第二个匹配的字符串时。
*/
public static String replaceSecond(String str, String target,
String replacement) throws NullPointerException, Exception {
if (str == null
------解决方案--------------------
target == null
------解决方案--------------------
replacement == null)
throw new NullPointerException();
int index = str.indexOf(target);
if (index == -1)
throw new Exception("Not Found.");
index = str.indexOf(target, index + target.length());
if (index == -1)
throw new Exception("Not Found.");
String str1 = str.substring(0, index);
String str2 = str.substring(index);
str2 = str2.replaceFirst("sss", "hello");
return str1 + str2;
}
------解决方案--------------------
话说因为你的img里面有需要转义的字符
str=str.replaceAll("(\\Q"+img+"\\E)(.*?)(\\1)(.*?)", "$1$2"+hello+"$4");
\Q \E之间的部分,代表里面的内容全是普通文本的引用,不要把它当作正则看待