Tuesday, March 1, 2011

how to detect links in a string using RegEx in as3 ?

I am trying to find the generic links in strings. I've found a very handy regex on RegExr, in the community expressions:

(https?://)?(www\.)?([a-zA-Z0-9_%]*)\b\.[a-z]{2,4}(\.[a-z]{2})?((/[a-zA-Z0-9_%]*)+)?(\.[a-z]*)?(:\d{1,5})?

I tried to use it and it returns null, although the same string tested on RegExr works fine:

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.google.com  google.com';
trace(linkRegEx.exec(link));//traces null

Is there anything I'm missing ?

From stackoverflow
  • you need to double the backslashes when you're using new RegExp. you might want to use the literal syntax, which doesn't impose such a requirement (assuming AS3 admits this syntax, I just know JS.

    Cory Petosky : Yes, AS3 allows literal RegExp syntax.
    George Profenza : backslashes fixed it. Thanks! That was quick!
    George Profenza : in case anyone else might be interested, I updated: "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");"
  • Looks like maybe you're trying to match the wrong variable? In line linkRegEx.exec(formattedStatus), formattedStatus isn't defined.

    George Profenza : sorry, wrong trace, that is fixed now

0 comments:

Post a Comment