JAVA正则表达式替换字符串问题

有一个字符串:String str = "第9条,数据错误,错误信息";
现在要将这个字符串中所有的“第*条”都通过替换为“第*行”
想用正则表达式实现?如何编写

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestRegex
{
public static void main( String[] args )
{
   String regex = "第[0-9]*条";
   String str = "第9条,数据错误,错误信息,第jjj哦条哦条我的条件如何?第221条xx";
   Pattern pat = Pattern.compile(regex);  
   Matcher matcher = pat.matcher(str);     
   while (matcher.find()) { 
     String temp = str.substring(matcher.start(),matcher.end());
     str = str.replaceAll(temp, temp.substring(0,temp.lastIndexOf("条"))+"行");
   }     
   System.out.println(str);
 }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-06
public class TestRegex {
public static void main(String[] args) {
String str = "第9条,数据错误,错误信息";
str = str.replaceAll("条", "行");
System.out.println(str);
}
}
第2个回答  2013-09-06
光把"条"替换成"行"会将"有5条"中的"条"也替换成"行",必须使用模式搜索才能保证正确
String ptn = "第\\d*(条)";
Pattern p = Pattern.compile(ptn, Pattern.DOTALL);
StringBuffer s = new StringBuffer().append("xx第9条,数据错误,错误信息, 第112条, no");
Matcher m = p.matcher(s);
while(m.find()) {
s = s.replace(m.start(1), m.end(1), "行");
}
return s;
第3个回答  2013-09-06
public static void main(String[] args) {
String str = "第9条,数据错误,错误信息";
System.out.println(str.replaceAll("第\\d行","第\\d条"));

}追问

你这个靠谱一点。
但是替换后的结果是:第d条,数据错误,错误信息。

是不是吧中间的值丢了啊????

你这个靠谱一点。
但是替换后的结果是:第d条,数据错误,错误信息。

是不是吧中间的值丢了啊????

追答

public static void main(String[] args) {
String str = "第92条,数据错误,错误信息";
System.out.println(str.replaceFirst("条","行"));//正则表达式替换正则表达式不行,最好能够采取first加一个限制,或者用replaceAll("条","行");
}

第4个回答  2013-09-06
str.replaceAll("条","行"); so easy!
相似回答