首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

正则表达式解决办法

2012-02-02 
正则表达式1.写出正则表达式,从一个字符串中提取链接地址。比如下面字符串中IT面试题博客中包含很多a hre

正则表达式
1.写出正则表达式,从一个字符串中提取链接地址。比如下面字符串中
"IT面试题博客中包含很多 <a href=http://hi.baidu.com/mianshiti/blog/category/微软面试题> 微软面试题 </a> "
则需要提取的地址为 " http://hi.baidu.com/mianshiti/blog/category/微软面试题 "

提示:<a\s+href=[^>]+?>





2. 一道面试题:编写正则表达式,验证由26个英文字母组成的字符串?






3.String str = "aaa[bbb[ccc,ddd[eee,fff]],ggg[hhh,iii]]";

要求,取出所有类似 xxx[xxx,xxx] 结构的字符串 ,

当然,这个最后的结果应该是  
aaa[bbb[ccc,ddd[eee,fff]],ggg[hhh,iii]]
bbb[ccc,ddd[eee,fff]]
ddd[eee,fff]
ggg[hhh,iii]

[解决办法]

string inputs = "IT面试题博客中包含很多 <a href=http://hi.baidu.com/mianshiti/blog/category/微软面试题> 微软面试题 </a> ";
string patterns = @"<a\s*href=(?<href>.*?[^>])>";
MatchCollection matches = Regex.Matches(inputs, patterns);
foreach (Match match in matches)
{
Console.WriteLine("href:{0}", match.Groups["href"].Value);
}
[解决办法]
囧,写错了。
第三题

C# code
string yourStr = "aaa[bbb[ccc,ddd[eee,fff]],ggg[hhh,iii]]";Regex regExp = new Regex(@"[^\[\],]+\[(((?<o>\[)|(?<-o>\])|[^\[\]])+(?(o)(?!)))\]");List<string> result = new List<string>(); Action<string> GetSubString = null;GetSubString = s =>    {        Match m = regExp.Match(s);        do        {            result.Add(m.Value);            if (regExp.IsMatch(m.Groups[1].Value))            {                GetSubString(m.Groups[1].Value);            }            m = m.NextMatch();        } while (m.Success);    };GetSubString(yourStr);result.ForEach(s => Console.WriteLine(s));/*输出aaa[bbb[ccc,ddd[eee,fff]],ggg[hhh,iii]]bbb[ccc,ddd[eee,fff]]ddd[eee,fff]ggg[hhh,iii]*/ 

热点排行