0

I have a string with the following format:

String str = "someString(anotherString)(lastString)";

I wanted to replace the lastString inside the last brackets, i.e new String should be

newStr = "someString(anotherString)(modified)";

I am using regex with "\\(([^\\}]+)\\)$" pattern.

But I am unable to change only the last content inside brackets. The above regex gives me the output:

"someString(modified)";

I just want to replace the content of the last brackets, any characters can appear infront of last bracket.

ANy help is appreciated.

1
  • What's the code you're using to replace it? Commented Jan 7, 2011 at 17:52

3 Answers 3

2

I think you have a typo in your expression. Replace the curly brackets with a regular one, and I think it will be fine.

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

Comments

1
yourString.replaceAll("(.+\\(.+\\)\\()[^\\}]+(\\)$)", "$1modified$2")

Comments

0
String resultString = subjectString.replaceAll(
    "(?x)\\(  # match opening parenthesis\n" +
    "[^()]*   # match 0 or more characters except parentheses\n" +
    "\\)      # match closing parenthesis\n" +
    "$        # match the end of the string", "(modified)");

So far, this is not allowing for whitespace between the closing parenthesis and the end of the string. You might want to insert a \\s* before the $ if you need to handle that case, too.

Comments

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.