problem of replaceAll()
I have wr开发者_如何学编程itten the following line of code:
str.replaceAll("xxx(ayyy)xxx", "$1".substring(0,1).equals("a") ? "a" : "b");
But I found that "$1".substring(0,1) will output "$" instead of "a". Is that any way to solve this problem?
The second parameter to replaceAll
is a regular string.
Java will evaluate your parameter before passing it to the function, not for each match.
"$1".substring(0,1)
simply returns the first character in the string $1
.
You need to call the appendReplacement
method of the Matcher
class in a loop.
If you want to apply different replacements for each match, use appendReplacement
/appendTail
:
Pattern p = Pattern.compile("xxx(ayyy)xxx");
StringBuffer out = new StringBuffer();
Matcher m = p.matcher("...");
while (m.find()) {
m.appendReplacement(out, m.group(1).substring(0, 1).equals("a") ? "a" : "b");
}
m.appendTail(out);
substring(start, end) will get you a substring from start till one before end. If you want to eliminate the first element try substring(1,lengthOfString)
精彩评论