有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java用捕获组替换所有

如果字符串的格式如下,我想在字符串中插入空格:

(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) 个答案

  1. # 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
    }
    
  2. # 2 楼答案

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