简体   繁体   中英

How can I manipulate part of a string in java using regular expressions

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM