加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

[C#正则表达式]正则表达式匹配组与使用正则表达式提取字符串

(2013-12-30 15:02:34)
标签:

正则表达式提取组

正则表达式提取字符串

it

分类: asp.net知识
//使用正则表达式匹配组
//需要引入命名空间using System.Text.RegularExpressions;

string s = "你是tom,我是jerry,他是韩梅梅,哈哈";
MatchCollection matches = Regex.Matches(s, @"是(\w+),");
//匹配组从0开始
for (int i = 0; i < matches.Count; i++)
{
      Match match = matches[i];
      //match.Value是匹配的内容
      Console.WriteLine(match.Value);

      string name = match.Groups[1].Value;
      Console.WriteLine(name);
}

//使用正则表达式提取字符串
          string s = "老王的英文名字是Wrong";
            Match match = Regex.Match(s, @"^(\w+)的英文名字是(\w+)$");
            //是否匹配成功
            if (match.Success)
            {
                //分组序号从1开始
                string cnName = match.Groups[1].Value;
                string enName = match.Groups[2].Value;
                Console.WriteLine(cnName);
                Console.WriteLine(enName);
            }
            string s = "June     26,  1951";
            Match match = Regex.Match(s, @"^([a-zA-Z]+)\s+\d{1,2},\s*\d{4}$");
            if (match.Success)
            {
                string month = match.Groups[1].Value;
                Console.WriteLine(month);
            }

            Match match = Regex.Match("大家好。我是S.H.E。我22岁了。我病了,呜呜。fffff", 
                "我是(.+)。");//+、*是贪婪的,会一直向后匹配,直到再贪婪一下后续就无法匹配为止。
            Match match = Regex.Match("大家好。我是S.H.E。我22岁了。我病了,呜呜。fffff",
                "我是(.+?)。");//+、*后加?表示“尽可能早的让后面的模式匹配”

            if (match.Success)
            {
                string name = match.Groups[1].Value;
                Console.WriteLine(name);
            }

            Console.ReadKey();

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有