开发者

Does regex allow you to parse strings? If so, how?

开发者 https://www.devze.com 2023-01-08 05:59 出处:网络
I\'ve used regex in the past for input validation, but I am wondering if they can let you parse a complex string.

I've used regex in the past for input validation, but I am wondering if they can let you parse a complex string.

I have a header 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 out say, the filename.

At the moment I am doing this (after parsing 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's hideous and ugly.

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

"+Name=Bob+Age=39+"

I can probably work out th开发者_开发问答e rest myself then.

Thanks.


Named matched subexpressions is what best suits your needs. (?<Name>Expression) allows you to access the string matching the expression Expression via the specified group name 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'.


Using Named Capturing Groups you should be able to parse just about anything and later refer to it by name.

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();


I think what you're looking for are Grouping Constructs, which allow you to extract parts of the regex. So using your simplified example:

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"]);
}


Give this a try:

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

精彩评论

暂无评论...
验证码 换一张
取 消