简体   繁体   English

在Java中使用正则表达式替换字符

[英]Replacing Character using Regular Expression in java

I have a String where a substring with third bracket can contain like that 我有一个String ,其中带有第三括号的子字符串可以包含这样的字符串

String str = "merSampleFactoryList[0].tfSendDate.fields[0].durationField.supported";

I want to replace all [0] , [1] , [2] ...... with " [] " . 我要替换所有[0] [1] [2] ......以“ [] I know i can do it using regular expression but don't know how to do that. 我知道我可以使用正则表达式来做,但是不知道该怎么做。

You can use String::replaceAll with regex \\[.*?\\] : 您可以将String :: replaceAll与正则表达式\\[.*?\\]

str = str.replaceAll("\\[.*?\\]", "[]")

Output 输出量

merSampleFactoryList[].tfSendDate.fields[].durationField.supported

regex demo 正则表达式演示


Note 注意

In case you want to replace only the bracket which contains integers then you can use \\[\\d+\\] instead. 如果只想替换包含整数的括号,则可以改用\\[\\d+\\]


Or like @Dukeling mention in comment you can use \\[[^]]*\\] instead of \\[.*?\\] 或像评论中提到的@Dukeling一样,您可以使用\\[[^]]*\\]代替\\[.*?\\]

regex demo 2 正则表达式演示2

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

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