randeepsp
randeepsp

Reputation: 3842

flex regex, add an avaliable string in regexp

In the below code if i replace st2 into the pattern of regexp without quotes, it works fine. Now since i get the regular expression from some other file, as it is shown in st2. I want to add that into the regexp pattern. But as in the below code it doesnt work.

<fx:Script>

import mx.controls.Alert

public function onClicking(){

    Alert.show("User says:" + textinput.text + " is new.");

}
public function checkValue(inputValue:String):void{

    var st2="[0-9]|[12][0-9]|3[01]";
    var pattern:RegExp = /^(st2)$/;
    var str:String = textinput.text;
    if(pattern.test(str)){
    Alert.show("pass");
    }
    else{
        Alert.show("fail");
    }



}
</fx:Script>

Upvotes: 0

Views: 1245

Answers (1)

Sly_cardinal
Sly_cardinal

Reputation: 13003

You will need to construct your RegExp from a string instead of using the regex literal.

Instead of creating your regex like this:

var st2="[0-9]|[12][0-9]|3[01]";
var pattern:RegExp = /^(st2)$/;

Create it like this:

var st2:String ="[0-9]|[12][0-9]|3[01]";
var pattern:RegExp = new RegExp("^(" + st2 + ")$");

Just be aware that you will need to be more careful with escaping (and double escaping) things like backslashes with this constructor though.

The reason is that the first notation is a regex literal - you putting in the value of the st2 variable, you are putting the literal text "st2" into the regex.

It might be clearer to look at it this way - imagine you had done this:

var st2:String ="123";
var st3:String = "abc st2";

It's clear that the st3 variable shouldn't contain "abc 123" - because you aren't referencing the st2 variable, you are putting in literal text instead. It's the same reason why it wasn't working with the RegExp literal notation (i.e. using the two forward slashes).

Upvotes: 2

Related Questions