question

Jeremy R avatar image
1 Like"
Jeremy R asked Phil BoBo edited

Assign Regular Expression to variable

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)?

FlexSim 18.2.3
flexsim 18.2.3regexregexpregular expression
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

1 Answer

·
Phil BoBo avatar image
1 Like"
Phil BoBo answered Phil BoBo edited

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);
· 2
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Jeremy R avatar image Jeremy R commented ·

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

0 Likes 0 ·
Phil BoBo avatar image Phil BoBo ♦♦ Jeremy R commented ·

@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");

regex_usercommand.fsm

2 Likes 2 ·
regex-usercommand.png (103.9 KiB)

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.