String.to_re?

I will explain you my problem, with a short example code:

···

a = "Good this kind of work!"
b = “this kind"
puts a[Regexp.new(“G.*#{b}.*rk!”)] >> Good this kind of work!”

a = "Good this+kind of work!"
b = "this+kind"
puts a[Regexp.new(“G.*#{b}.*rk!”)] >> nil

I woud like to know if you can implement a method string.to_re which converts a string to a regular expression, i.e.:

Good this+kind of work >>>> Good this[+]kind of work

Thank you very much for your wonderful Ruby!
Mattia Peronio

If you want to have some characters treated literally (if I understood
you properly), try Regexp.quote:
puts a[Regexp.new(Regexp.quote(“G.*#{b}.*rk!”))]

Gennady.

···

On Saturday, February 22, 2003, at 07:35 PM, Mattia Peronio wrote:

I will explain you my problem, with a short example code:


a = “Good this kind of work!”
b = “this kind”
puts a[Regexp.new(“G.*#{b}.rk!“)] >> Good this kind of
work!”
a = “Good this+kind of work!”
b = “this+kind”
puts a[Regexp.new("G.
#{b}.*rk!”)] >> nil

I woud like to know if you can implement a method string.to_re which
converts a string to a regular expression, i.e.:

Good this+kind of work >>>> Good this[+]kind of work

Thank you very much for your wonderful Ruby!
Mattia Peronio

Hi –

···

On Sun, 23 Feb 2003, Mattia Peronio wrote:

I will explain you my problem, with a short example code:


a = “Good this kind of work!”
b = “this kind”
puts a[Regexp.new(“G.*#{b}.*rk!”)] >> Good this kind of work!"

a = “Good this+kind of work!”
b = “this+kind”
puts a[Regexp.new(“G.*#{b}.*rk!”)] >> nil

I woud like to know if you can implement a method string.to_re which converts a string to a regular expression, i.e.:

Good this+kind of work >>>> Good this[+]kind of work

Try Regexp.escape:

Regex.new(Regexp.escape(“abc+def”)) # => /abc+def/

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

Hi,

···

At Sun, 23 Feb 2003 12:49:43 +0900, dblack@candle.superlink.net wrote:

I will explain you my problem, with a short example code:


a = “Good this kind of work!”
b = “this kind”
puts a[Regexp.new(“G.*#{b}.*rk!”)] >> Good this kind of work!"

a = “Good this+kind of work!”
b = “this+kind”
puts a[Regexp.new(“G.*#{b}.*rk!”)] >> nil

I woud like to know if you can implement a method string.to_re which converts a string to a regular expression, i.e.:

Good this+kind of work >>>> Good this[+]kind of work

Try Regexp.escape:

Regex.new(Regexp.escape(“abc+def”)) # => /abc+def/

In short:

puts a[/G.*#{Regexp.quote(b)}.*rk!/]

Ruby doesn’t have Perl-like \Q and \E.


Nobu Nakada