-3

重複の可能性:
C#正規表現を使用してHTMLタグを削除する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\" />"

次のコードは、最初のケースでは正常に機能しますが、2番目のケースでは機能しません。varpattern = @ "(\ 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;
        }
4

1 に答える 1

2

次のように、?(0または1)演算子を使用して、ステートメントをオプションとしてマークできます。

(CATEGORY=(?<category>\w*))?

これにより、の0回または1回の出現が検出されますCATEGORY=[WORD]

役立つと思われるその他の正規表現演算子は次のとおりです。

+(1以上)
*(0以上)

正規表現文字の詳細については、ここここを参照してください。

于 2012-07-02T21:11:09.923 に答える