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

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

问题描述

可能的重复:
如何使用 ActionScript 3 链接文本

我使用正则表达式在通用字符串中查找链接并突出显示该文本(下划线、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;
}

我将所有文本替换为链接".我想要与表达式匹配的相同文本而不是链接".我试过

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.

推荐答案

好的,我已经阅读了 replace() 方法.

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

有两个关键点:

  1. 您可以使用 $& 来获取匹配的子字符串.那里有很多方便且看起来很奇怪的符号.
  2. 替换时使用第二个字符串,否则您最终会陷入无限循环,并且时不时会产生黑色的小块.
  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;
}

正如 Cay 提到的,样式表更适合样式.感谢您的投入.

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

更新

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

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天全站免登陆