首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

当行匹配regex - C#时,停止添加到List<String>

在C#中,我们可以使用正则表达式(regex)来进行字符串的匹配和处理。当我们需要在处理文本时,根据特定的模式来匹配和提取字符串时,可以使用正则表达式。

要在C#中停止将匹配的字符串添加到List<String>中,我们可以使用循环来逐行读取文本,并使用正则表达式进行匹配。当匹配成功时,我们可以使用break语句来跳出循环,停止添加匹配的字符串到List<String>中。

下面是一个示例代码:

代码语言:txt
复制
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        List<string> matchedStrings = new List<string>();
        string pattern = "your_regex_pattern"; // 替换为你的正则表达式模式

        using (StreamReader reader = new StreamReader("your_file_path")) // 替换为你的文件路径
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (Regex.IsMatch(line, pattern))
                {
                    matchedStrings.Add(line);
                    break; // 当匹配成功时,停止添加匹配的字符串到List<String>中
                }
            }
        }

        // 输出匹配的字符串
        foreach (string matchedString in matchedStrings)
        {
            Console.WriteLine(matchedString);
        }
    }
}

在上述代码中,我们首先创建了一个List<String>对象来存储匹配的字符串。然后,我们定义了一个正则表达式模式(pattern),用于匹配我们想要的字符串。接下来,我们使用StreamReader来逐行读取文件内容,并使用Regex.IsMatch方法来判断当前行是否匹配正则表达式。如果匹配成功,则将该行添加到List<String>中,并使用break语句跳出循环,停止添加匹配的字符串。

请注意,你需要将"your_regex_pattern"替换为你的实际正则表达式模式,并将"your_file_path"替换为你的实际文件路径。

推荐的腾讯云相关产品和产品介绍链接地址:

  • 腾讯云正则表达式服务:https://cloud.tencent.com/product/regex
  • 腾讯云对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 腾讯云函数计算(SCF):https://cloud.tencent.com/product/scf
  • 腾讯云数据库(TencentDB):https://cloud.tencent.com/product/cdb
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券