日期:2014-05-20  浏览次数:20893 次

正则表达式
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]
*/