How to match the first occurrence of a character and split it

后端 未结 5 1291
忘掉有多难
忘掉有多难 2021-01-26 16:24

I have a text file from which I want to store Keys and Values in a String array.

In this case, Key is something like &

5条回答
  •  醉梦人生
    2021-01-26 16:28

    Here's one way to do it with regex (comments in code):

      string[] lines = {@"Input File : 'D:\myfile.wav'", @"Duration: 00:00:18.57"};
      Regex regex = new Regex("^[^:]+");
      Dictionary dict = new Dictionary();
    
      for (int i = 0; i < lines.Length; i++)
      {
        // match in the string will be everything before first :,
        // then we replace match with empty string and remove first
        // character which will be :, and that will be the value
        string key = regex.Match(lines[i]).Value.Trim();
        string value = regex.Replace(lines[i], "").Remove(0, 1).Trim();
        dict.Add(key, value);
      }
    

    It uses pattern ^[^:]+, which is negated class technique to match everything unless specified character.

提交回复
热议问题