当前位置: 移动技术网 > IT编程>开发语言>.net > C#初学36 字符串提取 贪婪模式

C#初学36 字符串提取 贪婪模式

2020年07月13日  | 移动技术网IT编程  | 我要评论
static void Main(string[] args)
{
    string str = "犯大货撒可富接电话萨科技和23432付款的说法2020来接收03 接口的了房间30";
    一般字符串提取不加^和$
    		--Regex.Match()只能提取一个匹配,结果为23432,后面的数字不提取
    Match match = Regex.Match(str, @"[0-9]+");
    Console.WriteLine(match.Value);
    		--Regex.Matches()提取字符中的所有匹配
    MatchCollection matches = Regex.Matches(str, "[0-9]+");
    foreach (var item in matches)
    {
        Console.WriteLine(item);
    }
    Console.ReadLine();
}
static void Main(string[] args)
{
    --从文件中提取字符串
    string email = File.ReadAllText("email.txt");
    --如果想对已经匹配的字符串再进行分组提取,就用到了"提取组"的功能
    --通过添加()就能实现提取组,()既有改变优先级的作用,又有提取组的功能
    (()(()))()  从左到右第一个(括号为第一组,第二个(为第二组,以此类推
    MatchCollection matches= Regex.Matches(email, @"([-a-zA-Z_0-9.])+@([-a-zA-Z_0-9.])+(\.[a-zA-Z]+)+");
    foreach (Match item in matches)
    {
        --item.Value表示本次提取到的字符串
        --item.Groups结合中存储的就是所有的分组信息
        --item.Groups[0]与item.Value是等价的都表示本次提取到的完整的字符串,表示整个邮箱字符串,而item.Groups[1].Value则表示第一组的字符串,以此类推。
        Console.WriteLine(item.Value);
        Console.WriteLine("第0组:{0}", item.Groups[0].Value);
        
        Console.WriteLine("第1组:{1}", item.Groups[1].Value);
        Console.WriteLine("第2组:{2}", item.Groups[2].Value);
    }
    Console.ReadLine();
}

贪婪模式

 static void Main(string[] args)
{
    --贪婪模式
    --贪婪: .+(默认贪婪模式,尽可能多的匹配)
    --非贪婪:.+?(尽可能少的匹配,1个)
    string str = "1111.1111.111111.111.11";
    Match match = Regex.Match(str,".+"); 尽可能多的去匹配,默认按照贪婪模式匹配
    Match match2 = Regex.Match(str, ".+?"); 挡在限定符之后使用?的时候,表示终止贪婪模式,会尽可能少的匹配
    Console.WriteLine(match.Value);
    Console.WriteLine(match2.Value);

    string str3 = "1111。1111。111111。111。11";
    Match match3 = Regex.Match(str3, ".+?.");  只匹配到1111。后面的不匹配
    Console.WriteLine(match3.Value);

    string str4 = "大家好,我们是S.H.E。我是光头、我是长舌妇、我是土豪,我是&西瓜(。看电视剧弗兰克jlkdfjl";
    MatchCollection matches = Regex.Matches(str4,"我是(.+)。");
    foreach (Match item in matches)
    {
        Console.WriteLine(item.Groups[1].Value); 输出结果为 光头、我是长舌妇、我是土豪,我是&西瓜(
    }
    Console.ReadKey();
}

本文地址:https://blog.csdn.net/Tianwen55/article/details/107253597

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网