Давайте попробуем Regex.Replace
, чтобы заменить все цитаты (я предположил, что цитата экранирована сама по себе: "abc""def" -> abc"def
) в строке:
string source = "\"24.09.2019\",\"545\",\"878\",\"5\"";
int index = 0;
string result = Regex.Replace(source, "\"([^\"]|\"\")*\"", m => $"\"{{{++index}}}\"");
Демо:
Func<string, string> convert = (source => {
int index = 0;
return Regex.Replace(source, "\"([^\"]|\"\")*\"", m => $"\"{{{++index}}}\"");
});
String[] tests = new string[] {
"abc",
"\"abc\", \"def\"\"fg\"",
"\"\"",
"\"24.09.2019\",\"545\",\"878\",\"5\"",
"name is \"my name\"; value is \"78\"\"\"\"\"",
"empty: \"\" and not empty: \"\"\"\""
};
string demo = string.Join(Environment.NewLine, tests
.Select(test => $"{test,-50} -> {convert(test)}"));
Console.Write(demo);
Результат:
abc -> abc
"abc", "def""fg" -> "{1}", "{2}"
"" -> "{1}"
"24.09.2019","545","878","5" -> "{1}","{2}","{3}","{4}"
name is "my name"; value is "78""""" -> name is "{1}"; value is "{2}"
empty: "" and not empty: """" -> empty: "{1}" and not empty: "{2}"
Редактировать: Вы можете легко разработать замену, например,если вы хотите заменить только целые числа
Func<string, string> convert = (source => {
int index = 0;
// we have match "m" with index "index"
// out task is to provide a string which will be put instead of match
return Regex.Replace(
source,
"\"([^\"]|\"\")*\"",
m => int.TryParse(m.Value.Trim('"'), out int _drop)
? $"\"{{{++index}}}\"") // if match is a valid integer, replace it
: m.Value); // if not, keep intact
});
В общем случае
Func<string, string> convert = (source => {
int index = 0;
// we have match "m" with index "index"
// out task is to provide a string which will be put instead of match
return Regex.Replace(
source,
"\"([^\"]|\"\")*\"",
m => {
// now we have a match "m", with its value "m.Value"
// its index "index"
// and we have to return a string which will be put instead of match
// if you want unquoted value, i.e. abc"def instead of "abc""def"
// string unquoted = Regex.Replace(
// m.Value, "\"+", match => new string('"', match.Value.Length / 2));
return //TODO: put the relevant code here
}
});