0

I have written 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?

3
  • Call me crazy, but what exactly is $1 there for? I don't see how this is relevant to whats going on. Commented Jan 27, 2010 at 2:19
  • 1
    I gather $1 is supposed to represent the group matched (ayyy) but Slaks has alredy said why that won't work. @Alan, try to tell us what you want to do rather than how you're trying to do it. There's almost always a better way :-) Commented Jan 27, 2010 at 2:21
  • @Anthony: It's supposed to match the first capture group from the regex. Commented Jan 27, 2010 at 2:22

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Good catch, @Slaks, I gather OP is trying to replace 'xxxNyyyxxx' with 'a' when N=='a' or 'b' when N!='a'. But since it's always 'a', they might as well just replace 'xxxayyyxxx' with 'a' and not fiddle around with groups.
@paxdiablo: I assume that that's only an example, and that he isn't replacing a hard-coded string.
Thanks very much for your clear explaination! I know what to do now. Thanks
3

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);

Comments

-2

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)

1 Comment

He realizes that; that's not his problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.