请问一个关于字符串替换的问题?

原字符串如下:sqrt{……},其中……为一个字符串
想替换为math.sqrt(……),原来的……要原封不动的包括在小括号里面,请问用java如何来实现?

如果我没理解错的话,sqrt{}有很多,但括号中的字符串却各不相同是吧?我的方法大概麻烦一些,抛砖引玉吧:
[code="java"]
String first = "sqrt{";
String splitBy = "splitBy";
String text =""; // 这里是你原来的文本,用io读取还是用什么办法自己替换就好。
// 先替换掉{,否则拆分时包括{可能出现正则语法不正确的问题
text = text.replace(first, "splitBy(");
// 根据不易重复的部分拆分开整个字符串
String strings[] = text.split(splitBy);
StringBuilder newText = new StringBuilder();
int count = 0;
// 若sqrt{不是原文本的开头,则先添加上原文本的开头。若是,则被split之后strings[0]为""
if (text.indexOf(splitBy) != 0) {
newText.append(strings[0]);
}
for(String string : strings) {
// strings[0]已经被处理过,跳过它
if (count == 0) {
count ++;
continue;
}
// split之后分隔符都会被忽略掉,加入正确的开头
newText.append("math.sqrt");
// 这里我认为你在sqrt{}中的字符串中不包含其他{}
newText.append(string.replaceFirst("}", ")"));
}
System.out.println(newText.toString());
[/code]

String oldOne = "sqrt{……}"; //假设
String newOne = oldOne.replaceFirst("sqrt{……}","math.sqrt(……)");//那么

一下子实现的方法没有
String odd = "sqrt{mm}";
String newword = odd.replace("sqrt{", "math.sqrt(").replace("}", ")");

我一般这样做

[code="java"]
public static String mathReplace(String fun) {
StringBuilder sb = new StringBuilder();
sb.append("math.");
int n = fun.length();
for (int i = 0; i < n; i++) {
char ch = fun.charAt(i);
switch (ch) {
case '{':
sb.append('(');
break;
case '}':
sb.append(')');
break;
default:
sb.append(ch);
}
}
return sb.toString();
}
[/code]