-3

Possible Duplicate:
Using C# regular expressions to remove HTML tags
Regex Pattern in C#

I have this kinda input how can i convert it into 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\" />"

Follwing code works fine for first case but not for second How can i Alter var pattern = @"(\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;
        }
Community
  • 1
  • 1
SOF User
  • 7,590
  • 22
  • 75
  • 121

1 Answers1

2

You can use the ? (0 or 1) operator to mark a statement as optional, like so:

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

This will find 0 or 1 occurrences of CATEGORY=[WORD].

Some other regex operators that you might find useful are:

+ (1 or more)
* (0 or more)

You can find more info on regex characters here and here.

Jon Senchyna
  • 7,867
  • 2
  • 26
  • 46