创建包含括号的正则表达式模式

时间:2018-01-11 07:53:57

标签: c# regex

我使用regexpattern突出显示与WPF中给定搜索条件匹配的文本。当用户键入San时,我的函数会创建一个模式(San)。在我的应用程序中的效果是搜索结果显示所有命中包含" San"用短语" San"突出显示。 但是,如果搜索字符串包含括号或反斜杠,例如" San("

创建正则表达式崩溃太多或太少'('或类似,因为模式将是(San()

创建模式使用Regex.Escape解决崩溃,但它也会转义初始括号。我可以在创建正则表达式后操作模式字符串,但是有更简化的方法吗?

private IEnumerable<Inline> CreateInlines(string text, string[] highlights)
    {
        var pattern = string.Join("|", highlights
            .Where(highlight => !string.IsNullOrEmpty(highlight))
            .Select(highlight => "(" + highlight + ")")
            .ToArray());

        if (string.IsNullOrEmpty(pattern))
        {
            yield return new Run(text);
            yield break;
        }

        var regex = new Regex(Regex.Escape(pattern), RegexOptions.IgnoreCase);
        var matches = regex.Matches(text);

        if (matches.Count < 1)
        {
            yield return new Run(text);
            yield break;
        }

        int offset = 0;
        for (int i = 0; i < matches.Count; i++)
        {
            var match = matches[i];
            if (match.Index > offset)
            {
                int length = match.Index - offset;
                yield return new Run(text.Substring(offset, length));
                offset += length;
            }

            if (match.Length > 0)
            {
                yield return new Run(text.Substring(offset, match.Length)) { Foreground = HighlightBrush };
                offset += match.Length;
            }
        }

        if (offset < text.Length)
        {
            yield return new Run(text.Substring(offset));
        }
    }

1 个答案:

答案 0 :(得分:1)

执行Regex.Escape此处:

    var pattern = string.Join("|", highlights
        .Where(highlight => !string.IsNullOrEmpty(highlight))
        .Select(highlight => "(" + Regex.Escape(highlight) + ")")
        .ToArray());

此外,C#6有字符串插值:

    var pattern = string.Join("|", highlights
        .Where(highlight => !string.IsNullOrEmpty(highlight))
        .Select(highlight => $"({Regex.Escape(highlight)})")
        .ToArray());

事实上,你根本不需要括号!您没有捕获任何内容(至少我没有看到您在代码中使用Groups。)

相关问题