正则表达式得到匹配和不匹配的部分

Regex get matched and unmatched parts

我有一个包含和标签的字符串。我知道用 Regex 解析 HTML 不是一个好的选择,但在这里因为我只能从 WYSIWYG 编辑器中获取少量标签,所以我使用这种方法。

我想要实现的是将字符串拆分为普通文本和标签。例如:

string str = "Hi I am normal text <strong>but bold</strong> and normal again";

我希望输出为:

[Hi I am normal text,
<strong>but bold</strong>, 
and normal again]

到目前为止,我已经尝试使用 (<[^<>]*>)<([^.>]+).*\s*><\s*([^.>]+)[^>]*>.*?<\s*/\s*\s*> 等各种表达式的组合来尝试正则表达式拆分和匹配,但其中 none 似乎有效

问题是 Regex.Split 还会输出捕获的子字符串和分割块。

在这种情况下,您需要连续查找匹配项,并随时将块添加到列表中:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var tststr = @"Hi I am normal text <strong>but bold</strong> and normal again";
        var lst = new List<string>();
        var former_idx = 0;
        for (var m = Regex.Match(tststr, @"(?s)\s*<(\w+)\b[^>]*>.*?</>\s*"); m.Success; m = m.NextMatch())
        {
            lst.Add(tststr.Substring(former_idx, m.Index - former_idx));
            lst.Add(m.Value);
            former_idx = m.Index + m.Value.Length;
        }
        if (former_idx < tststr.Length)
            lst.Add(tststr.Substring(former_idx, tststr.Length - former_idx));
        Console.WriteLine(string.Join("\n", lst));
    }
}

参见online C# demo and the regex demo

详情:

  • (?s) - RegexOptions.Singleline 选项内联选项使 . 跨行匹配
  • \s* - 零个或多个空格
  • < - 一个 < 字符
  • (\w+) - 第 1 组:一个或多个单词字符
  • \b - 单词边界
  • [^>]* - >
  • 以外的零个或多个字符
  • > - 一个 > 字符
  • .*? - 尽可能少的零个或多个字符
  • </> - </ + 第 1 组值 + >.
  • \s* - 零个或多个空格。