如何更换使用正则表达式在AS3文本的所有链接? [英] how do I replace all the links in a text using regex in as3?

查看:287
本文介绍了如何更换使用正则表达式在AS3文本的所有链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  如何使用ActionScript 3我linkify文本

我使用的是常规的前pression找到一个通用的字符串环节和突出显示文本(下划线,A HREF,任何东西)。

I am using a regular expression to find links in a generic string and highlight that text(underline, a href, anything).

这是我到目前为止有:

var linkRegEx:RegExp = new RegExp("(https?://)?(www\\.)?([a-zA-Z0-9_%]*)\\b\\.[a-z]{2,4}(\\.[a-z]{2})?((/[a-zA-Z0-9_%]*)+)?(\\.[a-z]*)?(:\\d{1,5})?","g");
var link:String = 'generic links: www.google.com http://www.yahoo.com  stackoverflow.com';
link = addLinks(linkRegEx,link);
textField.htmlText = link;//textField is a TextField I have on stage

function addLinks(pattern:RegExp,text:String):String{
    while((pattern.test(text))!=false){
        text=text.replace(pattern, "<u>link</u>");
    }
    return text;
}

我得到的所有与链接替换的文本。我想有一个是匹配前presion公司,而不是链接相同的文字。我试过

I get all the text replaced with "link". I'd like to have the same text that was matching the expresion instead of "link". I tried

text=text.replace(pattern, "<u>"+linkRegEx.exec(text)[0]+"</u>");

但我遇到了麻烦。我不认为我充分理解正则表达式和替代方法的工作。

but I ran into trouble. I don't think I fully understand how regex and the replace method work.

推荐答案

好吧,我读过了的更换()方法。

Ok, I've read the documentation for the replace() method.

有两个关键的东西:

  1. 您可以使用 $&安培; ,以获得匹配的子字符串。很多方便和怪异的有符号。
  2. 使用第二个字符串更换时,否则你最终在一个无限循环和小黑点wholes保持产卵飘飞。
  1. You can use $& to get the matched substring. A lot of handy and weird looking symbols there.
  2. Use a second string when replacing, otherwise you end up in an endless loops and tiny black wholes keep spawning every now and then.

下面是如何正确版本的功能如下:

Here's how the correct version of the function looks:

function addLinks(pattern:RegExp,text:String):String{
    var result = '';
    while(pattern.test(text)) result = text.replace(pattern, "<font color=\"#0000dd\"><a href=\"$&\">$&</a></font>");
    if(result == '') result+= text;//if there was nothing to replace
    return result;
}

由于礁提到的,样式是更多的样式apropiate。 感谢您的输入。

As Cay mentioned, a stylesheet is more apropiate for styling. Thanks for the input.

更新

上面列出的正则表达式时,链接包含#号不起作用。 下面是功能的更新版本:

The RegEx listed above doesn't work when links contain the # sign. Here's an updated version of the function:

function addAnchors(text:String):String{
    var result:String = '';
    var pattern:RegExp = /(?<!\S)(((f|ht){1}tp[s]?:\/\/|(?<!\S)www\.)[-a-zA-Z0-9@:%_\+.~#?&\/\/=]+)/g;
    while(pattern.test(text)) result = text.replace(pattern, "<font color=\"#0000dd\"><a href=\"$&\">$&</a></font>");
    if(result == '') result+= text;//if there was nothing to replace
    return result;
}

这篇关于如何更换使用正则表达式在AS3文本的所有链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆