Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create regular expression from string

Tags:

regex

ruby

Is there any way to create the regex /func:\[sync\] displayPTS/ from string func:[sync] displayPTS?

The story behind this question is that I have serval string pattens to search against in a text file and I don't want to write the same thing again and again.

 File.open($f).readlines.reject {|l| not l =~ /"#{string1}"/}
 File.open($f).readlines.reject {|l| not l =~ /"#{string2}"/}

Instead , I want to have a function to do the job:

  def filter string
          #build the reg pattern from string
          File.open($f).readlines.reject {|l| not l =~ pattern}
  end
  filter string1
  filter string2
like image 373
pierrotlefou Avatar asked Jan 05 '10 08:01

pierrotlefou


2 Answers

s = "func:[sync] displayPTS"
# => "func:[sync] displayPTS"
r = Regexp.new(s)
# => /func:[sync] displayPTS/
r = Regexp.new(Regexp.escape(s))
# => /func:\[sync\]\ displayPTS/
like image 145
Bob Aman Avatar answered Oct 31 '22 08:10

Bob Aman


How about using %r{}:

my_regex = "func:[sync] displayPTS"
File.open($f).readlines.reject { |l| not l =~ %r{#{my_regex}} }
like image 31
Priit Avatar answered Oct 31 '22 07:10

Priit