using variables in regular expressions

D

Damphyr

Being lazy, forgetful and generally very bad with regular expressions
leads me to post this question:

How can I use the contents of a variable as a pattern in a regular
expression?

I get a list of files from a set of paths and I want to do the following

repo=list_files paths
repo.collect!{|entry|
entry.gsub(/{variable_with_the root_I_want_to_substitute}/,"")
}

pretty straightforward no?
V.-



____________________________________________________________________
http://www.freemail.gr - äùñåÜí õðçñåóßá çëåêôñïíéêïý ôá÷õäñïìåßïõ.
http://www.freemail.gr - free email service for the Greek-speaking.
 
R

Robert Klemme

Damphyr said:
Being lazy, forgetful and generally very bad with regular expressions
leads me to post this question:

How can I use the contents of a variable as a pattern in a regular
expression?

I get a list of files from a set of paths and I want to do the following

repo=list_files paths
repo.collect!{|entry|
entry.gsub(/{variable_with_the root_I_want_to_substitute}/,"")
}

using gsub! is more efficient and better use %r{} because Regexp.quote
does not quote "/":

repo=list_files paths
repo.each {|entry|
entry.gsub!(%r{#{Regexp.quote(variable_with_the
root_I_want_to_substitute)}},"")
}

Regards

robert
 
S

Sabby and Tabby

Robert Klemme said:
using gsub! is more efficient and better use %r{} because Regexp.quote
does not quote "/":

repo.each {|entry|
entry.gsub!(%r{#{Regexp.quote(variable_with_the
root_I_want_to_substitute)}},"")
}

Don't need %r{}. A slash "/" in interpolated variables is harmless.
Add anchor, unless removing root from middle of path is desirable.
Add /o modifier:

entry.gsub!(/^#{Regexp.quote(root)}/o, "")
 
R

Robert Klemme

Sabby and Tabby said:
Don't need %r{}. A slash "/" in interpolated variables is harmless.
True.

Add anchor, unless removing root from middle of path is desirable.

I had that in my first version, but apparently the "^" didn't make it into
the posting. Thx!
Add /o modifier:

I wouldn't do that if the rx was in a method that received the path as
parameter. Could lead to surprising effects. :)
entry.gsub!(/^#{Regexp.quote(root)}/o, "")

Cheers

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top