在用到HTML编辑器的时候,我希望只能使用指定的元素,而其他的全部不允许使用,比如:
string pattern = "<[^font|span|div|table|td|th|a|embed|img|p|ol|ul|li|blockquote|h1|h2|h3|h4|h5|h6|pre|hr|br|tbody|tr|strong|b|sub|sup|em|i|u|strike|s|del]";
上面的那些元素是可用的,如可以使用<font>、<a>、<b>等等,但是如果是“<”后面不是上面那些元素,那么系统就把“<”替换为“&lt;”,那么这个正则表达式替换怎么写呢?
return System.Text.RegularExpressions.Regex.Replace(input, "这里是正则表达式", "这里怎么写?", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

解决方案 »

  1.   

    string result = Regex.Replace("你的HTML代码", "(?is)<(?!font|span|div|table|td|th|a|embed|img|p|ol|ul|li|blockquote|h1|h2|h3|h4|h5|h6|pre|hr|br|tbody|tr|strong|b|sub|sup|em|i|u|strike|s|del).*?>", "&lt;");
      

  2.   

    好像有点问题,我只想让最前面的“<”变成“&lt;”,后面的内容不变。
      

  3.   

    那更好办了
    直接将上面的正则改成这样
    (?is)<(?!font|span|div|table|td|th|a|embed|img|p|ol|ul|li|blockquote|h1|h2|h3|h4|h5|h6|pre|hr|br|tbody|tr|strong|b|sub|sup|em|i|u|strike|s|del)
    把后面的.*?>去掉就可以了