Chaos Project

RPG Maker => RPG Maker Scripts => Topic started by: Heretic86 on July 10, 2012, 03:34:44 am

Title: Variable in a Regular Expression?
Post by: Heretic86 on July 10, 2012, 03:34:44 am
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
 
Title: Re: Variable in a Regular Expression?
Post by: ForeverZer0 on July 10, 2012, 12:39:28 pm
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
Title: Re: Variable in a Regular Expression?
Post by: Heretic86 on July 10, 2012, 07:41:58 pm
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)
Title: Re: Variable in a Regular Expression?
Post by: ForeverZer0 on July 10, 2012, 08:41:42 pm
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.