【问题标题】:Cutting text from string after matching pattern匹配模式后从字符串中剪切文本
【发布时间】:2014-03-14 23:09:13
【问题描述】:

我想在下一个 <.br> 之前和最后一个 <.br> 之后剪切 <.br> 之后的所有文本,例如:

string example1 = "some example<br>text1<br>text2";
//do the magic
int match_count = 2;
string match1 = "text1";
string match2 = "text2";

如果不举一个实际的例子就很难解释这个;)

有没有一种简单的方法可以使用正则表达式来完成此任务?

附:更多使用示例:

string example1 = "some example<br>text1";
int match_count = 1;
string match1 = "text1";

string example2 = "some example";
int match_count = 0;

【问题讨论】:

    标签: c# regex winforms match


    【解决方案1】:

    一种不需要正则表达式的可能性是使用String.Split 重载之一:

    var input = @"some example<br>text1<br>text2";
    // split on every <br>
    var chunks = input.Split(new[] { "<br>" }, StringSplitOptions.RemoveEmptyEntries);
    // remove the first entry, everything else is wanted result
    foreach (var chunk in chunks.Skip(1))
    {
        Console.WriteLine(chunk);
    }
    

    输出是:

    text1
    text2
    

    然后您可以使用数组上的CountLength 轻松检查是否有任何匹配项。

    【讨论】:

      【解决方案2】:

      对于match_count,你可以只使用String.Split这样的方法;

      string example1 = "some example<br>text1<br>text2";
      int match_count = example1.Split(new[] { "<br>" }, 
                                       StringSplitOptions.RemoveEmptyEntries
                                      .Count() - 1;
      

      要在标签之间获取文本,看看这个问题;

      它在 vb.net 中,但您可以轻松地将其转换为 c#。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多