In a string i want to replace all words inside square bracket with its 3rd square block string

Manish Sharma :

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.

Wiktor Stribiżew :

You may use

\[phy\]\[[^\]\[]*\]\[([^\]\[]*)\]

and replace with $1. See the regex demo and the Regulex graph:

enter image description here

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91404&siteId=1