gpt4 book ai didi

java - 正则表达式转换将字符串转换为制表符分隔字段

转载 作者:行者123 更新时间:2023-11-30 03:44:51 24 4
gpt4 key购买 nike

我想将字符串转换为制表符分隔格式。我认为选项 1 应该可以。但看起来选项 2 实际上产生了预期的结果。有人能解释一下为什么吗?

public class test {
public static void main(String[] args) {
String temp2 = "My name\" is something";
System.out.println(temp2);
System.out.println( "\"" + temp2.replaceAll("\"", "\\\"") +"\""); //option 1
System.out.println( "\"" + temp2.replaceAll("\"", "\\\\\"") +"\""); //option 2
if(temp2.contains("\"")) {
System.out.println("Identified");
}
}
}

输出是:

My name" is something
"My name" is something"
"My name\" is something"
Identified

最佳答案

如果你想要Excel兼容的CSV格式,双引号的转义是两个个双引号,所以称为自转义。

String twoColumns = "\"a nice text\"\t\"with a \"\"quote\"\".";
String s = "Some \"quoted\" text.";
String s2 = "\"" + s.replace("\"", "\"\"") + "\"";

而且......计算反斜杠也不会让人头疼。

关于java - 正则表达式转换将字符串转换为制表符分隔字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25996495/

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