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?
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.