【问题标题】:Regex Pattern in C# [duplicate]C# 中的正则表达式模式 [重复]
【发布时间】:2012-07-03 07:17:14
【问题描述】:

可能重复:
Using C# regular expressions to remove HTML tags
Regex Pattern in C#

我有这样的输入,如何将其转换为 C#

Input = <!--EVENT-GALLERY-VIEW WIDTH=500 --> 
Output = "<widget:EventList id=\"EventList1\" Width=\"500\" runat=\"server\" />"

Input = <!--EVENT-GALLERY-VIEW WIDTH=500 CATEGORY=SPORTS --> 
Output = <widget:EventList id=\"EventList1\" Width=\"500\" runat=\"server\" Category=\"Sport\" />"

以下代码适用于第一种情况,但不适用于第二种情况 我如何更改 var 模式 = @"(\w*)(\s*))*(\s*)(-->)";

static void Main(string[] args)
        {
            var result = "<!--EVENT-GALLERY-VIEW WIDTH=500 -->";
            var pattern = @"(<!--)(\s*)(EVENT-GALLERY-VIEW)(\s*)((WIDTH)(=)(?<value>\w*)(\s*))*(\s*)(-->)|(<!--)(\s*)(EVENT-GALLERY-VIEW)(\s*)((WIDTH)(=)(?<value>\w*)(\s*))*(\s*)(-->)";
            var replaceTag = "<widget:EventList id=\"EventList@@id\" Width=\"@@value\" runat=\"server\" />";

            result = RegexReplaceWithUniqueTag(result, pattern, replaceTag);
        }

        static string RegexReplaceWithUniqueTag(string result, string pattern, string replaceTag)
        {
            Regex regex = new Regex(pattern);
            MatchCollection mc = regex.Matches(result);
            for (int i = mc.Count - 1; i >= 0; i--)
            {
                string newreplaceTag = replaceTag;
                newreplaceTag = newreplaceTag.Replace("@@id", i.ToString(CultureInfo.InvariantCulture));
                if (mc[i].Groups["value"] != null)
                    newreplaceTag = newreplaceTag.Replace("@@value", mc[i].Groups["value"].Value);
                result = result.Remove(mc[i].Index, mc[i].Length);
                result = result.Insert(mc[i].Index, newreplaceTag);
            }
            return result;
        }

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    您可以使用?(0 或 1)运算符将语句标记为可选,如下所示:

    (CATEGORY=(?&lt;category&gt;\w*))?

    这将找到 0 或 1 个 CATEGORY=[WORD]

    您可能会发现其他一些有用的正则表达式运算符是:

    +(1 个或多个)
    *(0 个或多个)

    您可以找到更多关于正则表达式字符herehere 的信息。

    【讨论】:

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