2011-03-14 57 views
1

我需要在下面的正则表达式上进行扩展,以便它还选择具有类的代码>标签,例如<。 < code class =“lol”>正则表达式帮助替换<html>标签

var text = 'This is <i>encoded text</i> but this is <b>bold</b >!'; 
var html = $('<div/>') 
    .text(text) 
    .html() 
    .replace(new RegExp('&lt;(/)?(b|i|u)\\s*&gt;', 'gi'), '<$1$2>'); 

任何人都可以帮忙吗?

我猜想像&lt;(/)?(b|i|u|code|pre)?(class="")\\s*&gt;

非常感谢

+9

不要使用正则表达式解析HTML/XML。为什么不使用jQuery的操纵器呢? – 2011-03-14 17:45:02

回答

3

解析与正则表达式的HTML是一个坏主意,看到这个answer

最简单的方法是简单地使用一些jQuery的dom操作函数来删除格式化。

$('<div/>').find("b, i, code, code.lol").each(function() { 
    $(this).replaceWith($(this).text()); 
}); 

jsfiddle代码示例。

0

我不会使用正则表达式来解析标记,但如果它只是一个字符串片段,这样的东西就足够了。应该指出,你使用的正则表达式使用\ s *来负担过重。它的可选形式可以通过开销并替换完全相同的东西。最好使用\ S +

正则表达式:<(/?(?:b|i|u)|code\s[^>]+class\s*=\s*(['"]).*?\2[^>]*?)\s+>
取代:<$1>
修饰符:sgi

<      # < Opening markup char 
    (      # Capture group 1 
     /?      # optional element termination 
     (?:      # grouping, non-capture 
      b|i|u     # elements 'b', 'i', or 'u' 
     )       # end grouping 
    |       # OR, 
     code      # element 'code' only 
     \s [^>]*     # followed by a space and possibly any chars except '>' 
     class \s* = \s*   # 'class' attribute '=' something 
     (['"]) .*? \2   # value delimeter, then some possible chars, then delimeter 
     [^>]*?     # followed by possibly any chars not '>' 
    )      # End capture group 1 
    \s+      # Here need 1 or more whitespace, what is being removed 
>      # > Closing markup char 
1

这一切替换整个标签在它(包括类,ID等):

.replace(new RegExp('&lt;(/)?(b|u|i|code|pre)(.*?)&gt;', 'gim'), '<$1$2$3>'); 

Mathing一个代码标签与类编码字符串是公顷当代码标签为固定格式时(<code class="whatever">),很容易:

.replace(new RegExp('&lt;(?:(code\\sclass=".*?")|(/)?(b|u|i|code|pre)(?:.*?))&gt;', 'gim'), '<$1$2$3>');