我的Java应用程序将获得以下形式的字符串:
How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan.
需要一个正则表达式/方法来删除[[ ]]
(和所有包含文本)的每个实例,从而将上面的字符串转换为:
How now. The arsonist feet. The a bank loan.
请注意保留的双重空格(arsonist
和feet
之间以及The
和a
之间)?这也很重要。
不确定此处的正则表达式是否合适,或者是否有更有效的方法来剔除不需要的[[ ]]
个实例。
答案 0 :(得分:3)
这是javascript。
var text = "How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan."
text.replace(/\[\[[^\]]+\]\]/g, "")
匹配大括号的正则表达式将是
/\[\[[^\]]+\]\]/g
所以Java等价物将是
text.replaceAll("\[\[[^\]]+\]\]", "");
并将其替换为空字符串
正则表达式,可以删除双括号和三个大括号
text.replaceAll("\[?\[\[[^\]]+\]\]\]?", "")
答案 1 :(得分:2)
使用replaceAll
str = str.replaceAll( "\\[\\[[^\\]]*\\]\\]", "" );
假设括号内没有]
。
答案 2 :(得分:2)
尝试使用此代码:
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);
}
}
希望这有帮助。
答案 3 :(得分:2)
tring s = "How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan.";
s=s.replaceAll("\\[.*?\\]","").replace("]","");
输出:
How now . The arsonist feet. The a bank loan.