如何从Java字符串中删除括号?

时间:2013-03-19 10:05:11

标签: java regex string

我的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.

请注意保留的双重空格(arsonistfeet之间以及Thea之间)?这也很重要。

不确定此处的正则表达式是否合适,或者是否有更有效的方法来剔除不需要的[[ ]]个实例。

4 个答案:

答案 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.