【问题标题】:how do I replace all the links in a text using regex in as3? [duplicate]如何在 as3 中使用正则表达式替换文本中的所有链接? [复制]
【发布时间】:2010-12-17 10:35:10
【问题描述】:

可能重复:
How do I linkify text using ActionScript 3

我正在使用正则表达式在通用字符串中查找链接并突出显示该文本(下划线、href、任何内容)。

这是我目前所拥有的:

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;
}

我将所有文本替换为“链接”。我想要与表达式匹配的相同文本,而不是“链接”。我试过了

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

但我遇到了麻烦。我不认为我完全理解正则表达式和替换方法的工作原理。

【问题讨论】:

    标签: regex flash actionscript-3 string


    【解决方案1】:

    好的,我已经阅读了replace() 方法的文档。

    有两个关键:

    1. 您可以使用 $& 来获取匹配的子字符串。那里有很多方便又奇怪的符号。
    2. 替换时使用第二个字符串,否则您将陷入无限循环,并且时不时会不断产生微小的黑色整体。

    以下是函数正确版本的外观:

    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;
    }
    

    正如 Cay 提到的,样式表更适合样式化。 感谢您的意见。

    更新

    当链接包含 # 符号时,上面列出的 RegEx 不起作用。 这是该函数的更新版本:

    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;
    }
    

    【讨论】:

      【解决方案2】:

      我读到here 在 AS3 中有一个替换函数,您可以在其中传递一个执行自定义操作的回调。这看起来比使用标准正则表达式捕获组更加灵活。

      【讨论】:

        【解决方案3】:

        如果您只需要在文本字段中为所有链接添加下划线,那么正确的做法应该是使用 StyleSheet... 尝试以下方式:

        var style:StyleSheet = new StyleSheet();
        style.setStyle("a", {textDecoration:"underline"});
        tf.styleSheet=style;
        tf.htmlText="hello <a href='#test'>world</a>";
        

        【讨论】:

        • 感谢您的提示。你做正确的事情是对的,但比下划线更重要的是拥有一个 href。在你的例子中:"tf.htmlText="hello world";"我希望将 #test 替换为模式匹配的字符串(例如 www.google.com、yahoo.com、stackoverflow.com 等)
        猜你喜欢
        • 2015-07-29
        • 2012-05-15
        • 2018-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多