1

I am writing a regular expression to replace a char from string.The char to be removed is decided at run time.So,is there any way to put variable in regex.

e.g- var reg:RegExp=/[some vaiable]/g;

I don't want to use the new operator to make regular expression.

Thanks in advance.

1 Answer 1

1

Unfortunately, your constraints make this impossible.

As per Adobe's help on regular expressions:

Forward slashes delineate a regular expression literal in the same way as quotation marks delineate a string literal.

and

When using the new constructor, you use two strings to define the regular expression. The first string defines the pattern

If you want the regex to be defined at runtime, i.e. not be literal, you have to use the second format. It's not at all hard!

var reg:RegExp = new RegExp(some_variable, "g");

It's exactly equivalent to what you want except for one major difference: this way works, while your way doesn't.

Sign up to request clarification or add additional context in comments.

4 Comments

i am already using the second format i.e using new constructor.I thought there may be other way to do this.
No, there isn't. The // syntax is only for literal expressions. Since you're inserting a variable into it, it's not literal, and you're stuck with the new syntax.
ok so we cant't insert a variable in regx literal exp. but we can insert a variable in string literal.
Technically, no. You don't insert a variable into a string literal, either. var str:String = "abcdesome_variablefghijklmnop" doesn't parse some_variable. You can do var str:String = "abcde" + some_variable + "efghijklmnop" - but that's constructing a string variable by concatenating 2 literals and a variable. Similarly in this case, you can't create a literal RegExp with a variable in it, but you can create one using a string variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.