Найти строки в кавычках и заменить содержимое между двойными кавычками - PullRequest
1 голос
/ 24 сентября 2019

У меня есть string, например,

"24.09.2019","545","878","5"

, которое должно быть обработано до

"{1}","{2}","{3}","{4}"

Теперь я пытаюсь использовать регулярное выражение :

string replacementString="{NG}";
Regex regex = new Regex("\\\"[0-9\.]+\\\"");    
MatchCollection matches = regex.Matches(originalString);

List<string> replacements = new List<string>();

for (int x = 0; x < matches.Count; x++)    
{    
    string replacement = String.Copy(replacementString);    
    replacement = replacement.Replace("NG", (x + 1).ToString());    
    replacements.Add(replacement);
    Match match = matches[x];
}

replacements.Reverse();

int cnt = 0;    

foreach (var match in matches.Cast<Match>().Reverse())    
{    
    originalStringTmp = originalStringTmp.Replace(
        match.Index, 
        match.Length, 
        replacements[cnt]);    

    cnt++;    
}

И

public static string Replace(this string s, int index, int length, string replacement)
{
    var builder = new StringBuilder();

    builder.Append(s.Substring(0, index));
    builder.Append(replacement);
    builder.Append(s.Substring(index + length));

    return builder.ToString();
 }

Но в этом случае результат будет

{1},{2},{3},{4}

Какое регулярное выражение следует использовать вместо

\"[0-9\.]+\"

для достижения результата

"{1}","{2}","{3}","{4}"

с регулярным выражением C #?

Ответы [ 2 ]

1 голос
/ 24 сентября 2019

Давайте попробуем 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
      }
  });
0 голосов
/ 24 сентября 2019
string originalString = "\"24.09.2019\",\"545\",\"878\",\"5\"";
var regex = new Regex("\"[0-9\\.]+\"");
var matches = regex.Matches(originalString);

string result = string.Join(',', Enumerable.Range(1, matches.Count).Select(n => $"\"{{{n}}}\""));

Ввод:

"24.09.2019", "545", "878", "5"

Результат:

"{1}", "{2}", "{3}", "{4}"

...