请教一个UBB转换代码中的正则问题。
如文本中有如下内容:
.http://www.9ele.com/..中<br />http://www.9ele.com/s<br />shttp://www.9ele.com/...
现在我想把所有链接都变成标准的A形式<a href="....">...</a>
我使用如下正则:
str = str.replace(/([a-zA-z]+:\/\/[\w%.-_\?&=\/,]+)/ig ,'<a href="$1" target="_blank">$1</a>');
str = str.replace(/\[url=([^\]]+)\]([^\[]+)\[\/url\]/ig, '<a href="$1" target="_blank">'+'$2'+'</a>');
str = str.replace(/\[url\]([^\[]+)\[\/url\]/ig, '<a href="$1" target="_blank">'+'$1'+'</a>');
这时就有一个问题了,因为第一个正则已经处理过了,第二三个正则再处理的时候就不正确了,反过来也是这样。
这时,我就想,能不能做前面限定,http://前面不能有“]”或者“=”。但是我怎么都写不出来。
请各位看看能怎么写才正确?
谢谢。

解决方案 »

  1.   

    嵌套处理比较复杂
    我采用的策略就是先匹配所有需要处理url的块,然后再分别处理各类情况
    避免互相影响
    var str = "http://www.csdn.nethttp://www.csdn.nethttp://www.csdn.net\
    http://www.csdn.net http://www.csdn.nethttp://www.csdn.net";function text2ubb(str, ext) {
        return str.replace(/\[(\w+)]\w+:\/\/[\w%.\-_\?&=\/,]+\[\/\1]|\[(\w+)=\w+:\/\/[\w%.\-_\?&=\/,]+][\s\S]*?\[\/\2]|\w+:\/\/[\w%.\-_\?&=\/,]+/g,
            function($0) {
                if (/^\w+:\/\/[\w%.\-_\?&=\/,]+$/.test($0))
                    if (ext)
                        return $0;
                    else return ["<a href=\"", $0, "\" target=\"_blank\">", $0, "</a>"].join("");
                var match = /^\[(\w+)](\w+:\/\/[\w%.\-_\?&=\/,]+)\[\/\1]$/.exec($0);
                if (match)
                    if (match[1] == "url")
                        return ["<a href=\"", match[2], "\" target=\"_blank\">", match[2], "</a>"].join(""); 
                    else if (match[1] == "img") 
                        return ["<img src=\"", match[2], "\"/>"].join("");
                match = /^\[(\w+)=(\w+:\/\/[\w%.\-_\?&=\/,]+)]([\s\S]*?)\[\/\1]$/.exec($0);
                if (match)
                    if (match[1] == "url")
                        return ["<a href=\"", match[2], "\" target=\"_blank\">", text2ubb(match[3], true), "</a>"].join(""); 
                    else if (match[1] == "img") 
                        return ["<img src=\"", match[2], "\"/>"].join("");
                return $0;
        });
    }
    document.open();
    alert(text2ubb(str));
    document.write(text2ubb(str));
    document.close();
      

  2.   

    输出
    <a href="http://www.csdn.net" target="_blank">http://www.csdn.net</a>
    <img src="http://www.csdn.net"/><a href="http://www.csdn.net" target="_blank">http://www.csdn.net</a>
    <a href="http://www.csdn.net" target="_blank">
    <img src="http://www.csdn.net"/>http://www.csdn.net</a>
    <a href="http://www.csdn.net" target="_blank">http://www.csdn.net</a> <img src="http://www.csdn.net"/><a href="http://www.csdn.net" target="_blank">http://www.csdn.net</a>
    <a href="http://www.csdn.net" target="_blank">http://www.csdn.net</a>