1

I have a string that looks like this:

String pathTokenString = "CMS/{brandPath}/Shows/{showPath}";

I want to remove the Shows part and everything that follows. I also want to replace "{brandPath}" with a token that I'm given.

This has been my approach. However, my string isn't getting updated at all:

//remove the '/Shows/{showPath}'
pathTokenString = pathTokenString.replace("/Shows$", "");

//replace passed in brandPath in the tokenString
String answer = pathTokenString.replace("{(.*?)}", brandPath);

Is there something wrong with my regular expressions?

2
  • 1
    /Shows$===>/Shows.*$ Commented May 1, 2015 at 17:50
  • @vks I just tried that and it didn't work. Is it a problem with using replace()? should I be using something else? Commented May 1, 2015 at 17:52

1 Answer 1

1

You should use the replaceAll method instead of replace when you want to pass a regex string as the pattern to be replaced. Also your regex patterns should be updated:

pathTokenString = pathTokenString.replaceAll("/Shows.*$", "");

// The curly braces need to be escaped because they denote quantifiers
String answer = pathTokenString.replaceAll("\\{(.*?)\\}", brandPath);
Sign up to request clarification or add additional context in comments.

2 Comments

this worked great. However, I had a quick follow-up. I now want to use a StringBuilder since I know it's not efficient to create all these strings. Is there an equivalent of replaceAll() for a StringBuilder? thanks!
@DanielD If it's just for these strings I don't really see how a StringBuilder could be more efficient. Your code is also more concise. Yet you can see stackoverflow.com/questions/3472663/….

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.