2010-11-29 49 views
0

我需要一些帮助,我有一些正则表达式。基本上我有一个只显示文字的留言框。我想用图像替换具有链接和图像网址的网址。我已经掌握了基础知识,只是当我尝试命名一个链接时,如果有多个链接,请检查demo正则表达式用链接替换url

命名链接格式{name}:url应该成为<a href="url">name</a>。我遇到的问题是在第5号喊话中,正则表达式不会正确地分割这两个URL。

HTML

<ul> 
<li>Shout #1 and a link to google: http://www.google.com</li> 
<li>Shout #2 with an image: http://i201.photobucket.com/albums/aa236/Mottie1/SMRT.jpg</li> 
<li>Shout #3 with two links: http://www.google.com and http://www.yahoo.com</li> 
<li>Shout #4 with named link: {google}:http://www.google.com</li> 
<li>Shout #5 with two named links: {google}:http://www.google.com and {yahoo}:http://www.yahoo.com and {google}:http://www.google.com</li> 
</ul> 

脚本

var rex1 = /(\{(.+)\}:)?(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g, 
    rex2 = /(http\:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g; 

$('ul li').each(function(i){ 
    var shout = $(this); 
    shout.html(function(i,h){ 
    var p = h.split(rex1), 
    img = h.match(rex2), 
    typ = (p[2] !== '') ? '<a href="$3">$2</a>' : '<a href="$3">link</a>'; 
    if (img !== null) { 
    shout.addClass('shoutWithImage') 
    typ = '<img src="' + img + '" alt="" />'; 
    } 
    return h.replace(rex1, typ); 
    }); 
}); 

更新:我想通了感谢布拉德帮助我的正则表达式。如果有人需要它,这里是updated demo和代码(现在在IE !!):

var rex1 = /(\{(.+?)\}:)?(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+)/g, 
rex2 = /(http:\/\/[\w\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[\w])+\.(?:jpg|png|gif|jpeg|bmp))/g; 

$('ul li').each(function(i) { 
    var shout = $(this); 
    shout.html(function(i, h) { 
    var txt, url = h.split(' '), 
    img = h.match(rex2); 
    if (img !== null) { 
     shout.addClass('shoutWithImage'); 
     $.each(img, function(i, image) { 
     h = h.replace(image, '<img src="' + image + '" alt="" />'); 
     }); 
    } else { 
     $.each(url, function(i, u) { 
     if (rex1.test(u)) { 
      txt = u.split(':')[0] || ' '; 
      if (txt.indexOf('{') >= 0) { 
      u = u.replace(txt + ':', ''); 
      txt = txt.replace(/[\{\}]/g, ''); 
      } else { 
      txt = ''; 
      } 
      url[i] = '<a href="' + u + '">' + ((txt == '') ? 'link' : txt) + '</a>'; 
     } 
     }); 
     h = url.join(' '); 
    } 
    return h; 
    }); 
}); 
+0

一你的问题是URL不能被任何东西分隔。这会让你的正则表达式非常复杂,因为它现在必须了解URL的格式。即使你将自己限制在http :,它仍然很难。 – Arkadiy 2010-11-29 22:36:48

+0

@Arkadiy:我无法控制什么人输入留言框=( – Mottie 2010-11-29 22:42:20

回答

2
(\{(.+?)\}:) 

您需要的?,使正则表达式成为“ungreedy”,而不仅仅是寻找下一个支柱。

编辑

但是,如果删除了{yahoo}:第二个链接变成空太(似乎填充锚标记,在短短无属性)。这似乎是使用拆分而不是替换的受害者。我几乎建议先做一次性寻找链接,然后回过头来寻找图像(我没有看到任何损害直接关联图像,除非这不是一个理想的结果?)