I have a string like " case 1 is good [phy][hu][get] my dog is [hy][iu][put] [phy][hu][gotcha]"
I want the result string as " case 1 is good get my dog is [hy][iu][put] gotcha "
Basically, I want all the substrings of the format [phy][.*][.*]
to be replaced with the content of the last (third) square bracket.
I tried using this regex pattern "\\[phy\\]\\.[^\\]]*]\\.\\[(.*?(?=\\]))]"
, but I am unable to think of a way that will solve my problem without having to iterate through each matching substring.
You may use
\[phy\]\[[^\]\[]*\]\[([^\]\[]*)\]
and replace with $1
. See the regex demo and the Regulex graph :
Details
\\[phy\\]
- [phy]
substring \\[
- [
char [^\\]\\[]*
- 0 or more chars other than [
and ]
\\]
- a ]
char \\[
- [
char ([^\\]\\[]*)
- Capturing group 1 ( $1
is its value in the replacement pattern) that matches zero or more chars other than [
and ]
\\]
- a ]
char Java usage demo
String input = "case 1 is good [phy][hu][get] my dog is [hy][iu][put] [phy][hu][gotcha]";
String result = input.replaceAll("\\[phy]\\[[^\\]\\[]*]\\[([^\\]\\[]*)]", "$1");
System.out.println(result);
// => case 1 is good get my dog is [hy][iu][put] gotcha
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.