",123456," // (2) ","abc,def"," -6ren">
gpt4 book ai didi

java - 删除 CSV 行的字符串引号中的逗号

转载 作者:行者123 更新时间:2023-11-30 09:21:10 27 4
gpt4 key购买 nike

目前,我倾向于删除 CSV 行的字符串中的逗号。

这是我的期望

    // (1) ",123,456,"     -> ",123456,"
// (2) ","abc,def"," -> ","abcdef","
// (3) ","123,456"," -> ","123456","
// (4) ","abcdef,"," -> ","abcdef","

我写了下面的代码

    String[] test = {
"\",123,456,\"",
"\",\"abc,def\",\"",
"\",\"123,456\",\"",
"\",\"abcdef,\",\""
};

final Pattern commaNotBetweenQuotes = Pattern.compile("(?<!\"),(?!\")");

for (String d : test) {
System.out.println("O : " + d);
String result = commaNotBetweenQuotes.matcher(d).replaceAll("");
System.out.println("R : " + result);
}

然而,我在情况(4)中失败了

这是我得到的输出

O : ",123,456,"
R : ",123456,"

O : ","abc,def","
R : ","abcdef","

O : ","123,456","
R : ","123456","

O : ","abcdef,","
R : ","abcdef,"," <-- we expect the comma after "f" being remove, as
it is inside string quote

我可以知道如何进一步改进这个正则表达式模式吗?

    final Pattern commaNotBetweenQuotes = Pattern.compile("(?<!\"),(?!\")");

我从Different regular expression result in Java SE and Android platform获取代码

我对模式的理解是

If a comma doesn't have double quote on its left AND on its right, replace it with empty string.

我尝试使用

     final Pattern commaNotBetweenQuotes = Pattern.compile("(?<!\"),(?!\")|(?<![\"0-9]),(?=\")");

有想法

If a comma doesn't have double quote on its left AND on its right, replace it with empty string.

OR

If a comma has double quote on its right, and non-digit / non double quote on its left, replace it with empty string.

然而,“解决方案”并不优雅。我真正想要的是,删除字符串文字中的逗号。删除整数中的逗号。保留用作 CSV 分隔符的逗号。

尽量不要使用$1,因为对于不匹配的组,Android 将使用“null”而不是“”。

最佳答案

描述

要替换所有卡在字符串中间的逗号,请使用以下内容,空捕获组 (\b) 应该避免 android 的问题,如果反向引用 $# 不匹配然后语言插入一个空字符而不是什么都不插入:

正则表达式:((?:",\d|\d,")|",")|(\b),

替换为:$1

enter image description here

输入

",123,456," 
","abc,def","
","123,456","
","abcdef,","

输出

",123456," 
","abcdef","
","123456","
","abcdef","

免责声明

假设您要保留的逗号都被引号包围,例如 "alpha","beta","1234"

关于java - 删除 CSV 行的字符串引号中的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17100167/

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