Variable in a Regular Expression?

Started by Heretic86, July 10, 2012, 03:34:44 am

Previous topic - Next topic

Heretic86

Is it possible to try to use a variable instead of an actual string in a Regular Expression?

IE

array = ['cat','dog','mouse']

arg = 'cats like milk'

for string in array
  arg.sub(/ string as a variable /) {print "found a matching string, or whatever"}
end
 
Current Scripts:
Heretic's Moving Platforms

Current Demos:
Collection of Art and 100% Compatible Scripts

(Script Demos are all still available in the Collection link above.  I lost some individual demos due to a server crash.)

ForeverZer0

I believe if you just change your syntax a bit it will work fine.

regex = /cats like milk/
for string in array
  arg.sub(regex) { print $1 }
end
I am done scripting for RMXP. I will likely not offer support for even my own scripts anymore, but feel free to ask on the forum, there are plenty of other talented scripters that can help you.

Heretic86

As it turns out, all I had to do was to pull the slashes out and string is treated as a variable and not a literal.   8)
Current Scripts:
Heretic's Moving Platforms

Current Demos:
Collection of Art and 100% Compatible Scripts

(Script Demos are all still available in the Collection link above.  I lost some individual demos due to a server crash.)

ForeverZer0

Exactly.
The slashes are just alternate syntax for creating a string. They are used for Regular Expression so that slashes, etc. are not parsed by the Ruby interpreter. Basically allows you to build strings without having to escape special characters.
I am done scripting for RMXP. I will likely not offer support for even my own scripts anymore, but feel free to ask on the forum, there are plenty of other talented scripters that can help you.