简体   繁体   English

如何使用正则表达式在Java中处理字符串的一部分

[英]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. 我还想用获得的令牌替换“ {brandPath}”。

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. 当您要将正则表达式字符串作为要替换的模式时,应使用replaceAll方法而不是replace 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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