本文介绍了的replaceAll不替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想要的文字REPLACEME要换成我StringBuffer的符号。当我打印的符号,它是一个有效的字符串。当我打印我的查询,它仍然有文字REPLACEME,而不是符号。为什么呢? 私人字符串BuildQuery对于(){    查询字符串= "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";    deserializeQuotes();    StringBuffer的符号=新的StringBuffer();    的for(int i = 0; I&LT; quotes.size();我++){        如果(ⅰ==(quotes.size() - 1))            symbols.append(%22+ quotes.get(ⅰ).getSymbol()+%22%); //以引号结束        其他            symbols.append(%22+ quotes.get(ⅰ).getSymbol()+%22%2C);    }    的System.out.println(*** ***符号+ symbols.toString());    query.replaceAll(REPLACEME,symbols.toString());    返回查询;}解决方案 修改 query.replaceAll(REPLACEME,symbols.toString());到 查询= query.replaceAll(REPLACEME,symbols.toString()); 在Java字符串被设计成不变。这就是为什么的replaceAll()不能代替字符的在当前字符​​串,因此它必须返回一个新字符串的字符替换。如果你想简单地替换文字,不需要正则表达式的语法支持使用同样替换而不是的replaceAll (正则表达式语法的支持是这两种方法之间的唯一区别)。它是安全的,你会在情况下,要替换文字可以包含正则表达式元字符像 * , + , [,] 的等的。I want the text "REPLACEME" to be replaced with my StringBuffer symbols. When I print symbols, it is a valid string. When I print my query, it still has the text REPLACEME instead of symbols. Why?private String buildQuery(){ String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="; deserializeQuotes(); StringBuffer symbols = new StringBuffer(); for(int i = 0; i < quotes.size();i++){ if(i == (quotes.size()-1)) symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote else symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C"); } System.out.println("***SYMBOLS***" + symbols.toString()); query.replaceAll("REPLACEME", symbols.toString()); return query;} 解决方案 Change query.replaceAll("REPLACEME", symbols.toString());to:query = query.replaceAll("REPLACEME", symbols.toString());Strings in Java are designed to be immutable.That is why replaceAll() can't replace the characters in the current string, so it must return a new string with the characters replaced.Also if you want to simply replace literals and don't need regex syntax support use replace instead of replaceAll (regex syntax support is only difference between these two methods). It is safer in case you would want to replace literals which can contain regex metacharacters like *, +, [, ] and others. 这篇关于的replaceAll不替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-11 16:45