Regular expression allows you to parse strings? If so, how?

I used regex in the past to validate input, but I wonder if they can let you parse a complex string.

I have a headline like this:

-----------------------------7dac1d2214d4\r\nContent-Disposition: form-data; name=\"my_title\"\r\n\r\nMyData\r\n-----------------------------7dac1d2214d4\r\nContent-Disposition: form-data; name=\"myupload\"; filename=\"C:\\myfile.zip\"\r\nContent-Type: application/x-zip-compressed\r\n\r\n

I want to be able to parse, say, a file name.

I am currently doing this (after parsing the headers):

this.FileName = headers[1].Substring(headers[1].IndexOf("filename=\"") + "filename=\"".Length, headers[1].IndexOf("\"\r\n", headers[1].IndexOf("filename=\"")) - (headers[1].IndexOf("filename=\"") + "filename=\"".Length));

But it is disgusting and ugly.

Can regex solve this problem more elegantly? I understand the basics of syntax, so if it can solve it, can someone show me how to parse this with a regex:

"+Name=Bob+Age=39+"

I probably can solve the rest myself then.

Thank.

+3
source share
4 answers

Named Capturing Groups, , .

var inputString = "+Name=Bob+Age=39+";
var regex = new Regex("Name=(?<Name>[A-Z][a-z]*)\\+Age=(?<Age>[0-9]*)");

var match = regex.Match(inputString);

System.Console.WriteLine("Name: {0}", match.Groups["Name"]);
System.Console.WriteLine("Age: {0}", match.Groups["Age"]);

System.Console.ReadKey();
+2

- , . (?<Name>Expression) , Expression, Name.

var input = "Foo=42;Bar='FooBar'";

var regex = new Regex(@"Foo=(?<Foo>[0-9]+);Bar='(?<Bar>[^']+)'");

var match = regex.Match(input);

Console.WriteLine(match.Groups["Foo"]); // Prints '42'.
Console.WriteLine(match.Groups["Bar"]); // Prints 'FooBar'.
+4

:

(?<=filename\=\").*(?=\")
0

, Grouping Constructs, . , :

string input = @"+Name=Bob+Age=39+";
Regex regex = new Regex(@"Name=(?<Name>[^\+]+)\+Age=(?<Age>[^\+]+)");

foreach (Match match in regex.Matches(input))
{
    Console.WriteLine("Name = '{0}'", match.Groups["Name"]);
    Console.WriteLine("Age  = '{0}'", match.Groups["Age"]);
}
0

Source: https://habr.com/ru/post/1755501/


All Articles