2012-07-02 4 views
-3

가능한 중복 : 나는 C 번호로 변환 할 수있는 방법 나는이 좀 입력이
Using C# regular expressions to remove HTML tags
Regex Pattern in 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을 코드 작품 첫 번째 경우는 괜찮지 만 두 번째 경우는 그렇지 않다. 어떻게 할 수 있습니까? 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=\"[email protected]@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; 
     } 

답변

2

당신은과 같이 선택적으로 ? (0 또는 1) 운영자가 표시 할 수있는 문을 사용할 수 있습니다 :

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

CATEGORY=[WORD]의 0 또는 1 항목을 찾을 수 있습니다. 당신이 유용하게 찾을 수 있습니다

다른 어떤 정규식 연산자는 다음과 같습니다

+ (1 이상)
* (0 이상)

당신은 정규식 문자 herehere에 대한 추가 정보를 찾을 수 있습니다.