My Java app will be getting strings of the following form:
How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan.
And need a regex/method that would strip out every instance of [[ ]]
(and all inclusive text), thus turning the above string into:
How now. The arsonist feet. The a bank loan.
Notice the preserved double-spaces (between arsonist
and feet
, and between The
and a
)? That's important too.
Not sure if a regex here is appropriate or if there is a more efficient way of culling out the unwanted [[ ]]
instances.
This is in javascript.
var text = "How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan."
text.replace(/\[\[[^\]]+\]\]/g, "")
The regex to match the braces will be
/\[\[[^\]]+\]\]/g
So Java equivalent will be
text.replaceAll("\[\[[^\]]+\]\]", "");
and replace it with an empty string
regex which can remove both double and triple braces
text.replaceAll("\[?\[\[[^\]]+\]\]\]?", "")
This is simple with replaceAll
str = str.replaceAll( "\\[\\[[^\\]]*\\]\\]", "" );
Assumes no ]
between the brackets.
Try using this code :
public class Test{
public static void main(String[] args) {
String input = "How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan.";
// Will replace all data within braces []
String replaceAll = input.replaceAll("(\\[.+?\\])|(\\])", "");
System.out.println(replaceAll);
}
}
Hope this helps.
tring s = "How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan.";
s=s.replaceAll("\\[.*?\\]","").replace("]","");
Output:
How now . The arsonist feet. The a bank loan.
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.