简体   繁体   English

在Java中将{替换为“”?

[英]Replacing { with “”, in java?

I have a string like this: 我有一个像这样的字符串:

{ TestAddCardForMerchant }

I wish to replace { , } with "" . 我希望将{}替换为"" Is it possible to do so? 有可能这样做吗?

Using the String.replaceAll() method and the "[{}]" regular expression: 使用String.replaceAll()方法"[{}]"正则表达式:

String replaced = "{ TestAddCardForMerchant }".replaceAll("[{}]","\"");

The String replaced will be " TestAddCardForMerchant " . replaced的字符串将为" TestAddCardForMerchant "

如果您只需要将{}替换为pair。

String result = str.replaceAll("\\{([^}]+)\\}", "\"$1\"");

应该这样做:

myString.replaceAll("[{}]", "\"");

You can use String#replaceAll method to replace all ocurrences of {} from your string.. [] in [{}] is used to denote character class.. It means { or } .. 您可以使用字符串#的replaceAll方法替换所有ocurrences {}从您的字符串.. []中的[{}]用来表示字符类..这意味着{} ..

Also, you need to escape " with a backslash, as it has special meaning in Java.. So, here's is your regex, to achieve what you need :- 另外,您需要用反斜杠转义" ,因为它在Java中具有特殊含义。.因此,这是您的正则表达式,可以实现所需的功能:

"{test}".replaceAll("[{}]", "\"")

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

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