views:

110

answers:

5

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. ???? }

A: 

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.

PhiLho
+1  A: 

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

var nut:String = ut.replace(pattern, "$1");
AnthonyWJones
Just tried your suggestion. Unfortunately, still same result.
Todd
A: 

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.

yuku
Thanks. I appreciate the help.
Todd
+1  A: 

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.

Virusescu
Also, in order for your first pattern with \w to work, if you write it between quotes, then you must escape the \ char. Else it would work only if written likevar pattern:RegExp = /X=(\w+)/;
Virusescu
Thanks a bunch! All the wrinkles to learning a new language :-)
Todd
A: 
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.

bug-a-lot