gpt4 book ai didi

Java正则表达式替换双引号内的双引号

转载 作者:行者123 更新时间:2023-11-29 05:57:06 25 4
gpt4 key购买 nike

输入字符串是:“引号内的外部字符串””
输出应该是:"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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com