Reputation: 69
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.
Upvotes: 3
Views: 65
Reputation: 626747
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 ]
charJava 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
Upvotes: 4