Todd
Todd

Reputation: 746

What's wrong with my ActionScript Regex?

I am trying pull a field out of a string and return it.

My function:

public function getSubtype(ut:String):String {
            var pattern:RegExp = new RegExp("X=(\w+)","i");
            var nut:String = ut.replace(pattern, "$1");
            trace("nut is " + nut);
            return nut;
        }

I'm passing it the string:

http://foo.bar.com/cgi-bin/ds.pl?type=boom&X=country&Y=day&Z=5

the trace statements return the above string with out modification.

I've tried the pattern out on Ryan Swanson's Flex 3 Regular Expresion Explorer and it returns: X=country. My wished for result is "country".

Must be obvious, but I can't see it. Any help will be appreciated.

TB

changed my function to the following and it works:

public function getSubtype2(ut:String):String {
            trace("searching " + ut);
            var pattern:RegExp = new RegExp("X=([a-z]+)");
            var r:Object = pattern.exec(ut);
            trace("result is " + r[1]);
            return r[1].toString();

Interestingly, though, using X=(\w+) does not match and causes an error. ???? }

Upvotes: 1

Views: 386

Answers (5)

bug-a-lot
bug-a-lot

Reputation: 2454

var pattern : RegExp = /[\\?&]X=([^&#]*)/g;
var XValue : String = pattern.exec(ut)[1]; 

See http://livedocs.adobe.com/flex/3/langref/RegExp.html#exec%28%29 for further explanations.

I have also found this flex regexp testing tool to be quite helpful.

Upvotes: 0

Virusescu
Virusescu

Reputation: 394

The replace method is used for replacing. That is if you want to modify the given string. Replacing given portion with his own occurrence produces the same string. I think you are looking for the match method, that produces an array of matches, see below.

function getSubtype(ut:String):String {
            var pattern:RegExp = new RegExp("X=([a-z]+)","i");
            var nut:Array = ut.match(pattern);
            trace("nut is " + nut[1]);
            return nut[1];
}

nut[0] beeing the full matched string, followed by nut[1] the first brackets group and so on.

Upvotes: 1

Instead of

 var pattern:RegExp = new RegExp("X=(\w+)","i");

You can write this:

 var pattern:RegExp = /X=(\w+)/i;

Then you will not have problems with backslashes.

Upvotes: 0

AnthonyWJones
AnthonyWJones

Reputation: 189457

The replace method does not mutate the string it operates on, it returns a new string. Try:-

var nut:String = ut.replace(pattern, "$1");

Upvotes: 1

PhiLho
PhiLho

Reputation: 41132

Note: I don't know ActionScript...

Your RE Explorer seems to return the matched pattern, see if there is a possibility to see the captures as well.

And if AS behaves like most languages I know, your replace() call replaces X=country with country.

Upvotes: 0

Related Questions