c#在字符串中搜索特定的模式,并放入数组中

本文关键字:模式 数组 字符串 搜索 | 更新日期: 2023-09-27 17:50:40

我有以下字符串为例:

<tr class="row_odd"><td>08:00</td><td>08:10</td><td><a href="editactivity.php?act=11111">TEST1</a></td></tr><tr class="row_even"><td>08:10</td><td>08:15</td><td><a href="editactivity.php?act=22222">TEST2</a></td></tr><tr class="row_odd"><td>08:15</td><td>08:20</td><td><a href="editactivity.php?act=33333">TEST3</a></td></tr><tr class="row_even"><td>08:20</td><td>08:25</td><td><a href="editactivity.php?act=44444">TEST4</a></td></tr><tr class="row_odd"><td>08:25</td><td>08:30</td><td><a href="editactivity.php?act=55555">TEST5</a></td></tr>

我需要将输出作为一维数组。如11111=myArray(0), 22222=myArray(1), 33333=myArray(2),......

我已经尝试了myString。替换,但似乎我只能用这种方式替换一个Char。所以我需要使用表达式和for循环来填充数组,但由于这是我的第一个c#项目,这对我来说是一个太远的桥梁。

谢谢,

c#在字符串中搜索特定的模式,并放入数组中

看起来您想使用Regex搜索模式。然后将匹配项(使用命名组)返回到数组中。

var regex = new Regex("act='?(<?Id>'d+)");
regex.Matches(input).Cast<Match>()
     .Select(m => m.Groups["Id"])
     .Where(g => g.Success)
     .Select(g => Int32.Parse(g.Value))
     .ToArray();

(PS。我对regex模式不太肯定——你应该自己检查一下)

有几种方法可以做到这一点。有几个是:

a)使用正则表达式在字符串中查找所需的内容。使用了命名组,因此可以直接访问匹配项
http://www.regular-expressions.info/dotnet.html

b)在子字符串所在的位置分割表达式(例如在"act="上分割)。您将不得不做更多的解析来得到您想要的,但这不会很难,因为它将在分割字符串的开始(以及您的其他字符串,其中没有您的子字符串)

使用IndexOf和Substring的组合…类似这样的东西可以工作(不确定字符串变化多少)。这可能比你想到的任何正则表达式都要快。虽然,看看字符串的长度,这可能不是一个真正的问题。

    public static List<string> GetList(string data)
    {
        data = data.Replace("'"", ""); // get rid of annoying "'s
        string[] S = data.Split(new string[] { "act=" }, StringSplitOptions.None);
        var results = new List<string>();
        foreach (string s in S)
        {
            if (!s.Contains("<tr"))
            {
                string output = s.Substring(0, s.IndexOf(">"));
                results.Add(output);
            }
        }
        return results;
    }

使用HTML标签拆分字符串,如"<tr>","</tr>","<td>","</td>", "<a>","</a>"strinng-variable.split()函数。这给了你一个数组列表。

将html行拆分为字符串数组