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?

DanielD
  • 1,315
  • 4
  • 17
  • 25

1 Answers1

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);
M A
  • 71,713
  • 13
  • 134
  • 174
  • 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 May 01 '15 at 18:20
  • 1
    @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 http://stackoverflow.com/questions/3472663/replace-all-occurences-of-a-string-using-stringbuilder. – M A May 01 '15 at 18:26