用捕获组替换所有

时间:2011-06-23 07:23:20

标签: java regex

如果字符串采用以下任何格式,我想将空格插入字符串:

(A)   => (A)
(A)B  => (A) B
A(B)  => A (B)
A(B)C => A (B) C
AB(C) => AB (C)

提前谢谢。

编辑:只有在匹配的括号中才能进行替换。

AB(C => AB(C should remain as is.

2 个答案:

答案 0 :(得分:1)

这不完全是你做的,但差不多。这将在括号括起来的所有内容之前和之后添加空格。任何现有空间将被一个空格所取代。最后还删除尾随空格。

备注:我只检查了模式(顺便说一下在Eclipse中),可能会有一些小的语法错误。

String addParentheses(String text) {       
        Pattern ps = Pattern.compile("(\\s)*(\\([^\\)]*\\))(\\s)*"); //Find everything surrounded by (), 'eating' the spaces before and after as well.
        Matcher m=ps.matcher(text);
        StringBuffer output = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(output, " $1 ");  //Surround with spaces, replacing any existing one 
        }

        m.appendTail(output);
        return output.toString().trim(); //Remove trailing spaces
}

答案 1 :(得分:-2)

String s = "AB(C)"; // This is your input
s.replaceAll("(", " (");
s.replaceAll(")", ") ");
s = s.trim();