[英]Replace all with capturing group
如果字符串采用以下任何格式,我想将空格插入字符串:
(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.
这与您所做的不完全相同,但几乎可以做到。 这将在括号周围的所有内容之前和之后添加空格。 任何现有空间将被一个空间代替。 最后,最后的空格也被删除。
备注:我仅检查了模式(顺便说一下,在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
}
String s = "AB(C)"; // This is your input
s.replaceAll("(", " (");
s.replaceAll(")", ") ");
s = s.trim();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.