字符串函数 - 如果一个字符位于两个其他字符之间,则替换该字符的实例

String function - replace instances of a character if they are between two other characters

我 运行 一个巨大的 SQL 查询,我不想再次 运行 并将结果保存为 csv。我正在 C# 控制台应用程序中进行一些处理,将每条记录添加到存储 table。不幸的是,我搞砸了,没有删除 ','s from the results, and there are some objects serialized in JSON in this data which contain ','。

我已经在遍历所有这些数据,以便我的列正确排列我只想暂时将“,”转换为“;”,但前提是它位于字符串中的大括号之间。例如:

ID,InputModel,Type
1,{"address":"11th street"},true
2,{"address":"11th street, new york"},true

我的代码如下:

for (int j = 0; j < allLines.Length; j++)
{                    
    string line = allLines[j];
    // would like to replace ',' with ';' if between curly braces
    string[] data = line.Split(',');
    myInsertMethod(data);
}

想要的结果:

ID,InputModel,Type
1,{"address":"11th street"},true
2,{"address":"11th street; new york"},true

您可以使用以下正则表达式匹配花括号内的逗号:

(?<=\{[^}]*),(?=[^}]*\})

可以用分号代替:

var rgx = new Regex(@"(?<=\{[^}]*),(?=[^}]*\})");
var result = rgx.Replace("{word, word}, {word, word}", ";");

结果:{word; word}, {word; word}

您的代码:

private static readonly Regex rgx = new Regex(@"(?<=\{[^}]*),(?=[^}]*\})", RegexOptions.Compiled);
...
for (int j = 0; j < allLines.Length; j++)
{                    
    var line = allLines[j];
    var data = rgx.Replace(line, ";").Split(',');
    myInsertMethod(data);
}

在 Expresso 中测试: