From: Dennis Newbold Date: 2002-05-17T02:38:20+09:00 Subject: Re: How to Convert Regex Back to String in Exact Match? Hi Bill, Well, its not a very elegant way to do it, but with the assumption that saving alot of your time is worth more than saving a little bit of computer memory, I'd probably add a couple of new methods to the RegExp class called something like Regexp::save_originating_string and Regexp::recover_originating_string. Then, each time you call Regexp::new(string), you can follow it with a call to Regexp::save_originating_string(string), passing the same string to both. If you want to be slightly more elegant, and cut down on possibilities for human error, you could create a new class called (for example) RRegexp, which would be a subclass of Regexp. (yes, I don't much like that name either, but I'm too lazy or unimaginative to think of a good one. I'm sure you can come up with a much better one on your own). In any case, RRegexp.new would squirrel away its argument in an instance variable, and then call self.super, returning the results to the caller (well, message sender in OO terms). In this case, you would not need the save_originating_string method, but just the recover_originating_string method. Hope this helps. Dennis On Thu, 16 May 2002, William Djaja Tjokroaminata wrote: > Hi, > > Some time ago, I posted the question on "How to Convert String to Regex to > Perform Exact Match". The problem is to generate a regex "reg" from > string "str" such that these two are equivalent: > > someString == str > > someString =~ reg > > and the answer is > > reg = Regexp.new('\A' + Regexp.escape(str) + '\z') > > Now, given a regex "reg" that was created from a string "str" such as > above, is there any simple way to recover str back from reg? I know that > in general it is impossible to convert a regex into a string. However, in > the special case such as above (we know how reg was created from str), is > there an easy way to convert reg to str? > > Basically, I need the inverse of the method escape. I can remove '\A' > and '\z' without any problem, but I don't know how to deal with all the > replacements that have been done by the method escape. Thanks. > > Regards, > > Bill >