TutorialWhen you use rich text box to add information, if you directly use copy and paste, if the copy is incomplete or otherwise, html tags may not be paired, if not, when the information is directly displayed on the page, if the page also uses unpaired tags in the original information, it may cause page confusion, therefore, this method is used to check whether tag pairs are complete and automatically add unpaired tags.
1 2 public string AutoCheckHtml (string htmlStr) 3 { 4 string checkTags = "table, tbody, tr, td, p, div, span "; 5 Stack st = new Stack (); 6 Regex regStart = new Regex (@ "<(? <Tag> [\ w] +) [\ s \ S] *?> "); 7 Regex regEnd = new Regex (@ "<\/(? <Tag> [\ w] +) [\ s \ S] *?> "); 8 9 StringBuilder sb = new StringBuilder (); 10 11 string tagName; 12 foreach (string s in htmlStr. Split ('<')) 13 { 14 // filter first string that have no' <' 15 if (sb. Length = 0) 16 { 17 sb. Append (""); 18 continue; 19} 20 Match m; 21 // recode start tag 22 if (m = regStart. Match ("<" + s). Success && 23 (tagName = m. Groups ["tag"]. Value )! = ""&& 24 checkTags. IndexOf (tagName. ToLower ())! =-1) 25 { 26 st. Push (tagName ); 27} 28 // process end tag 29 else if (m = regEnd. Match ("<" + s). Success && 30 (tagName = m. Groups ["tag"]. Value )! = ""&& 31 checkTags. IndexOf (tagName. ToLower ())! =-1) 32 { 33 // have no start tag 34 if (st. Count = 0 | st. Peek (). ToString ()! = TagName) 35 { 36 sb. AppendFormat ("<{0}> \ r \ n", tagName ); 37} 38 else 39 st. Pop (); 40} 41 sb. Append ("<" + s ); 42} 43 // Add end tags 44 while (st. Count> 0) 45 { 46 sb. AppendFormat ("</{0}> \ r \ n", st. Pop ()); 47} 48 return sb. ToString (); 49} |
1. checkTags is the label to be checked, and only those listed in it will check
2. regStart and regEnd the regular expression of the start tag and the end tag (the regular expression written in the Code may not match some situations and can be supplemented based on actual needs)
Another related processing method is the paging of rich text. For example, if it is intercepted directly based on the string length, it may be truncated from the middle of the tag or separated from the end tag, based on the above principles, you can write code for smart paging. haha. wait for time to write it out and paste it again!
Original article: http://www.cnblogs.com/hanf/archive/2009/08/16/1547020.html