代码之家  ›  专栏  ›  技术社区  ›  grenade

帮助使用标签删除正则表达式

  •  2
  • grenade  · 技术社区  · 16 年前

    public static void RemoveTagWithKey(this string message, string tagKey) {
        if (message.ContainsTagWithKey(tagKey)) {
            var regex = new Regex(@"\[" + tagKey + @":[^\]]");
            message = regex.Replace(message , string.Empty);
        }
    }
    public static bool ContainsTagWithKey(this string message, string tagKey) {
        return message.Contains(string.Format("[{0}:", tagKey));
    }
    

    只应从字符串中删除具有指定键的标记。我的正则表达式不起作用,因为它很愚蠢。我需要帮助才能把它写好。或者,欢迎不使用正则表达式的实现。

    4 回复  |  直到 16 年前
        1
  •  1
  •   AAT    16 年前

    我知道现在有更多功能丰富的工具,但我喜欢它的简单性和整洁性 Code Architects Regex Tester (又名YART:又一个正则表达式测试器)。以树状图显示组和捕获,非常快,非常小,开源。它还可以用C++、VB和C#生成代码,并可以自动转义或取消转义这些语言的正则表达式。我将其转储到我的VS工具文件夹(C:\Program Files\Microsoft Visual Studio 9.0\Common7\tools)中,并在“工具”菜单中用“工具”为其设置一个菜单项>外部工具,这样我就可以从VS内部快速启动它。

    正则表达式有时很难编写,我知道能够测试正则表达式并在过程中看到结果真的很有帮助。

    alt text
    dotnet2themax.com )

    另一个非常受欢迎(但不是免费)的选择是 Regex Buddy .

        2
  •  3
  •   Dale    16 年前

    如果你想在没有正则表达式的情况下做到这一点并不难。您已经在搜索特定的标记键,因此您可以只搜索“[”+tagKey,然后从那里搜索结束“]”,并删除这些偏移之间的所有内容。类似。..

    int posStart = message.IndexOf("[" + tagKey + ":");
    if(posStart >= 0)
    {
        int posEnd = message.IndexOf("]", posStart);
        if(posEnd > posStart)
        {
            message = message.Remove(posStart, posEnd - posStart);
        }
    }
    

    编辑: IndexOf()解决方案被视为更好的另一个原因是,它意味着只有一个规则来查找标签的开头,而原始代码使用 Contains()

        3
  •  1
  •   Drew Noakes    16 年前

    请尝试以下操作:

    new Regex(@"\[" + tagKey + @":[^\]+]");
    

    我唯一改变的是添加 + [^\] 模式,意味着您匹配一个或多个不是反斜杠的字符。

        4
  •  1
  •   Alan Moore Chris Ballance    16 年前

    我想这就是你要找的正则表达式:

    string regex = @"\[" + tag + @":[^\]+]\]";
    

    public static string RemoveTagWithKey(string message, string tagKey) {
        string regex = @"\[" + tag + @":[^\]+]\]";
        return Regex.Replace(message, regex, string.Empty);
    }
    

    你似乎在编写一个扩展方法,但我将其作为一个静态实用方法来编写,以保持简单。