Assign Regular Expression to variable

Assign Regular Expression to variable

jeremy_r
Not applicable
133 Views
3 Replies
Message 1 of 4

Assign Regular Expression to variable

jeremy_r
Not applicable

[ FlexSim 18.2.3 ]

Functions like string.match() and string.replace() can use regular expressions. According to the documentation, regular expressions are actually of the RegExp type. However, RegExp doesn't appear to be a valid type for a variable. i.e. the following code does not work

RegExp expression = /[0-9]/;

Is there any way to assign a regular expression to a variable? Or are all regular expressions required to be defined directly in the code?

The key reason I wanted to do this was to be able to dynamically construct a regular expression in code. Is there any way to do that in FlexScipt (e.g. constructing a string, then converting that string to a regular expression)?

Accepted solutions (1)
134 Views
3 Replies
Replies (3)
Message 2 of 4

philboboADSK
Autodesk
Autodesk
Accepted solution

You cannot dynamically construct a regular expression in FlexScript currently.

They can only be used as literals directly in the code where you are using them.

You cannot store them in a variable, return them from a function, or construct them from a string.

EDIT: If you build up the entire function call, then you can use executestring() to execute it. You can't execute just the regex part though, because you can't return a regex from a function. You must execute the entire function:

string text = "blue cars are really green.";
string findPattern = "/blue/gi";
if (uniform(0, 1) > 0.5)
    findPattern = "/green/gi";
string replaceWith = "red";

var function_with_regex = "eventdata.as(string).replace(" + findPattern + ", \"" + replaceWith + "\")";
return executestring(function_with_regex, 0, 0, text);


Phil BoBo
Sr. Manager, Software Development
Message 3 of 4

jeremy_r
Not applicable

Alright, that's disappointing, but pretty much what I expected. Thanks for the direct answer.

0 Likes
Message 4 of 4

philboboADSK
Autodesk
Autodesk

@jeremy.r

You can wrap the syntax of that example into a user command so that your usage of it is cleaner:

return stringReplaceRegEx("blue cars are really green.", "/blue/gi", "red");

32407-regex-usercommand.png

regex_usercommand.fsm



Phil BoBo
Sr. Manager, Software Development