gpt4 book ai didi

java - 使用 java Regex 将逗号替换为字符串中的任何特殊字符

转载 作者:行者123 更新时间:2023-12-02 06:49:03 25 4
gpt4 key购买 nike

我想用 java 中双引号内的任何一个特殊字符(例如“#”)替换所有逗号。

下面是字符串:

String line="\"Lee, Rounded, Neck, Printed\",410.00,300.00,\"Red , Blue\",lee";

输出:

"Lee# Rounded# Neck# Printed",410.00,300.00,"Red # Blue",lee

我已经尝试过这个:

public class Str {
public static void main(String[] args) {
String line="\"Lee, Rounded, Neck, Printed\",410.00,300.00,\"Red , Blue\",lee";
String lineDelimiter=",";
String templine=line;
if(templine!=null && templine.contains("\""))
{
Pattern p=Pattern.compile("(\".*?"+Pattern.quote(lineDelimiter)+".*?\")");
Matcher m=p.matcher(templine);
if(m.find())
{
for (int i = 1; i <= m.groupCount(); i++) {
String Temp=m.group(i);
String Temp1=Temp;
Temp=Temp.replaceAll("(,)", " ## ");
line=line.replaceAll(Pattern.quote(Temp1),Pattern.quote(Temp));
}
}
}
}
}

使用上面的代码,我只能找到引号内出现的字符串的第一次出现,而不是第二次出现(“Red , Blue”)。

最佳答案

以下代码应该有效:

String line="\"Lee, Rounded, Neck, Printed\",410.00,300.00,\"Red , Blue\",lee";
String repl = line.replaceAll(",(?!(([^\"]*\"){2})*[^\"]*$)", "#");
System.out.println("Replaced => " + repl);

输出:

"Lee# Rounded# Neck# Printed",410.00,300.00,"Red # Blue",lee

说明:此正则表达式基本上意味着如果逗号后面没有偶数个双引号,则匹配逗号。换句话说,如果逗号位于双引号内,则匹配逗号。

PS:假设没有不平衡的双引号,也没有转义双引号的情况。

关于java - 使用 java Regex 将逗号替换为字符串中的任何特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18258527/

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