Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove all inside square brackets

As a title I’m trying to remove all inside square brackets from a string.
If I’ve for example a string like:

"This is a [value1] string within some [image-nnnn] stuff between square  [image] brackets"

I would achieve this result:

"This is a string within some stuff between square brackets"

Could be possible use regex like this to find and remove that stuff?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val pattern = Pattern.compile("\\[(.*?)\\]")

Or need I to find and replace manually?
Thanks in advance

EDIT:
The code above not working because not find any maches when I execute:
patter.matcher("This is a [value1] string within some [image-nnnn] stuff between square [image] brackets").matches()

>Solution :

Your regex is on the right track, but I would use this version:

String input = "This is a [value1] string within some [image-nnnn] stuff between square  [image] brackets";
String output = input.replaceAll("\\s*\\[.*?\\]\\s*", " ").trim();
System.out.println(output);

// This is a string within some stuff between square brackets

The regex pattern \s\[.*?\]\s* also matches any whitespace on either side of the bracketed term, replacing by a single space. This correctly splices together the two halves of the sentence. Then we trim to remove any leading/trailing whitespace.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading