Home > Blockchain >  How to parse INT values in brackets
How to parse INT values in brackets

Time:08-07

How can I parse the INT contents of this string, and add to List ?

Files[file1.jpg[2066654],file2.png[234235],file3.gif[56476788]]

That way I can call fields, like list.Filename, list.Filesize

Its a custom string im using to group files in a txt file, so I want to extract these values out : filename (with extension), and size (int)

How can I do this? I've tried

var filename = str.Substring(str.LastIndexOf('Files[')   1).str.Substring(str.LastIndexOf(']'));

But I have no way of getting this especially in this type of format. Any suggestions?

Thanks!

CodePudding user response:

Regex is your friend here.

Try this:

var regex = new Regex(@"^Files\[((?'name'(.*?))\[(?'length'(\d ))\],?)*\]$");

var input = "Files[file1.jpg[2066654],file2.png[234235],file3.gif[56476788]]";

var match = regex.Match(input);
var names = match.Groups["name"].Captures.Cast<Capture>();
var lengths = match.Groups["length"].Captures.Cast<Capture>();

var output =
    names
        .Zip(lengths, (f, n) => new
        {
            file = f.Value,
            length = int.Parse(n.Value)
        })
        .ToArray();

That gives me:

file length
file1.jpg 2066654
file2.png 234235
file3.gif 56476788
  •  Tags:  
  • c#
  • Related