62,616
社区成员
发帖
与我相关
我的任务
分享
Pattern p1 = Pattern.compile("seo");
Matcher m1 = p1.matcher("seo kkk seo 999 seo jjj seo seo");
StringBuffer buf = new StringBuffer();
m1.find(1); //随便替换出现seo的位置
m1.appendReplacement(buf, "888");
m1.appendTail(buf);
println(buf);
public static void main(String[] args) {
String reg = "seo";
String replace = "8888";
String str = "aaa seo kkk seo ";
System.out.println(replaceFirst(str, reg, replace));
}
public static String replaceFirst(String str, String from, String to) {
int len = from.length();
int offset = str.indexOf(from);
if (offset < 0)
return str;
StringBuffer sb = new StringBuffer();
sb.append(str.substring(0, offset));
sb.append(to);
sb.append(str.substring(offset + len));
return sb.toString();
}
public static void main(String[] args){
String reg = "seo";
String replace = "8888";
String str = "aaa seo kkk seo ";
int index = str.indexOf(reg);
if(index != -1){
str = str.substring(0,index) + replace + str.substring(index+reg.length());
}
System.out.println(str);
}