C# RegEx string extraction

前端 未结 5 694
孤街浪徒
孤街浪徒 2020-12-05 06:06

I have a string:

\"ImageDimension=655x0;ThumbnailDimension=0x0\".

I have to extract first number (\"655\" string) coming in be

5条回答
  •  误落风尘
    2020-12-05 06:51

    Since a lot of people already gave you what you wanted, I will contribute with something else. Regexes are hard to read and error prone. Maybe a little less verbose than your implementation but more straightforward and friendly than using regex:

    private static Dictionary _extractDictionary(string str)
    {
        var query = from name_value in str.Split(';')   // Split by ;
                    let arr = name_value.Split('=')     // ... then by =
                    select new {Name = arr[0], Value = arr[1]};
    
        return query.ToDictionary(x => x.Name, y => y.Value);
    }
    
    public static void Main()
    {
        var str = "ImageDimension=655x0;ThumbnailDimension=0x0";
        var dic = _extractDictionary(str);
    
        foreach (var key_value in dic)
        {
            var key = key_value.Key;
            var value = key_value.Value;
            Console.WriteLine("Value of {0} is {1}.", key, value.Substring(0, value.IndexOf("x")));
        }
    }
    

提交回复
热议问题