c#正则表达式 特殊格式内容的提取

我的命题是在类似格式“ToDo[123.125+a-b,2]”的格式中,提取123.125+a-b和2.前者为表达式,后者格式为纯数值。

代码:

string pattern = @"(?<=^round\[|^roundup\[|^rounddown\[)(?<number>.+)[,](?<digit>\d+)(?=\]$)";
Match mt = Regex.Match(textBox3.Text, pattern, option);
var a = mt.Groups["number"].Value;
var b = mt.Groups["digit"].Value;

当textBox3的text为“round[100.23,5]”时,最后a为100.23,b为5.

当textBox3的text为“round[(round[100.23,5]),5]”时,最后a为(round[100.23,5]),b为5.

当textBox3的text为“round[abcdefs]”时,也就是没有匹配值时,最后a为“”,b为“”.

前面一个贪婪匹配,后一个只匹配数值,正是我想要的结果。

作为保留,用时再温习。

 

一起贴上微软官方的代码:

string urlPattern = @"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/";
Console.WriteLine();
Console.Write("Enter a URL for data parsing: ");
string url = Console.ReadLine();
Regex urlExpression = new Regex(urlPattern, RegexOptions.Compiled);
Match urlMatch = urlExpression.Match(url);
Console.WriteLine("The Protocol you entered was " +
urlMatch.Groups["proto"].Value);
Console.WriteLine("The Port Number you entered was " +
urlMatch.Groups["port"].Value);

 运行上面的例程时,结果为:

Enter a URL for data parsing: http://server.com:2100/home.aspx 
The Protocol you entered was http 
The Port Number you entered was :2100 

posted @ 2012-09-19 14:29  脸谱匠  阅读(866)  评论(0编辑  收藏  举报