gpt4 book ai didi

c# - 字符串中不带逗号的单引号替换

转载 作者:行者123 更新时间:2023-11-30 13:54:53 27 4
gpt4 key购买 nike

假设,我有以下字符串:

string str = "'Hello, how are you?', 'your name', what you want";

我可以用以下内容替换单引号和逗号:

str.Replace("'", "''");
string[] word = str.Split(',');

我想知道我怎样才能得到像下面这样的输出:

Hello, how are you? your name what you want

单引号内的逗号不会被替换,只会被替换掉。

最佳答案

您可以使用正则表达式完成此操作:

private const string SPLIT_FORMAT = "{0}(?=(?:[^']*'[^']*')*[^']*$)";
public static string SplitOutsideSingleQuotes(this string text, char splittingChar)
{
string[] parts = Regex.Split(text, String.Format(SPLIT_FORMAT, splittingChar), RegexOptions.None);
for (int i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Replace("'", "");
}

return String.Join("", parts);
}

代码使用表达式在单引号外的 splittingChar 上进行拆分。然后它替换结果字符串数组中的每个单引号。最后,它将各个部分重新组合在一起。

关于c# - 字符串中不带逗号的单引号替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38651652/

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