输入字符串是:“引号内的外部字符串””
输出应该是:"outer string inside a quote "
请建议使用任何正则表达式来查找内部双引号并使用 Java 替换为空格。
最佳答案
您可以这样尝试,不用正则表达式,并且在一次迭代中:
/*
* I assume that if after quote ther is character like "a then it is
* beggining of cite. Rest quotes are closing ones.
*/
public static String removeInnerQuotes(String data) {
StringBuilder sb = new StringBuilder();
int quoteCounter = 0;
char[] array = data.toCharArray();
for (int i = 0; i < array.length; i++) {
if (array[i] == '"') {
if (i + 1 < array.length
&& (
(array[i + 1] >= 'a' && array[i + 1] <= 'z')
||
(array[i + 1] >= 'A' && array[i + 1] <= 'Z')
)
){
quoteCounter++;
if (quoteCounter == 1)
sb.append('"');
}
else{
quoteCounter--;
if (quoteCounter == 0)
sb.append('"');
}
} else
sb.append(array[i]);
}
return sb.toString();
}
public static void main(String[] args) {
String data = "\"outer string \"inside a quote\" abc\" something outside quote, and again \"outer string \"inside a quote\" def \"";
System.out.println(removeInnerQuotes(data));
}
输出:
“引号 abc 内的外部字符串” 引号外的东西,再次“引号 def 内的外部字符串”
关于Java正则表达式替换双引号内的双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11649389/