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

不问归期 提交于 2019-12-31 03:05:08

问题


I ran a massive SQL query that I don't want to run again and saved the results as a csv. I am doing some processing in a C# console app that adds each record to a storage table. Unfortunately, I messed up and did not remove ','s from the results, and there are some objects serialized in JSON in this data which contain ','.

I am already looping through all this data, and so that my columns correctly line up I would just like to temporarily convert ',' to say ';', but only if it is between curly braces in the string. For example:

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

My code is as follows:

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);
}

Desired result:

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

回答1:


You can match a comma inside curly braces using the following regex:

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

You can replace it with a semi-colon:

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

Result: {word; word}, {word; word}

Your code:

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);
}

Tested in Expresso:



来源:https://stackoverflow.com/questions/29799644/string-function-replace-instances-of-a-character-if-they-are-between-two-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!