我得到了字符串“('allan', 'bob's', 'charles', 'dom')”
。现在我需要这个字符串,但格式为 "('allan', 'bob''s', 'charles', 'dom')"
。
请注意,我已将 bob's
替换为 bob''s
,仅此而已。我最初的解决方案是这样的
String str = "('allan', 'bob's', 'charles', 'dom')";
String[] elements = str.substring(1, str.length()-1).split(", ");
String res = "(";
for (int j = 0; j < elements.length; j++) {
res += "'"+ elements[j].substring(1, elements[j].length()-1).replace("'", "''") + "'" + ((j == elements.length - 1) ? ")" : ",' ");
}
其中 res 是最终的解决方案。不过我想知道是否有一个更短、更优雅的解决方案?
最佳答案
replaceAll 将使用 "'s"
作为正则表达式。
public static void main(String[] args) {
String str = "('allan', 'bob's', 'charles', 'dom')";
str = str.replaceAll("'s", "''s");
System.out.println(str);
}
输出:
('allan', 'bob''s', 'charles', 'dom')
关于java - 替换字符串中重复字符的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612426/