Kevin
Kevin

Reputation: 1614

Get string from Regex in Ruby

I need to add a string to a regular expression in ruby, this is what Im trying to do (Im getting all the files in my directory, opening them, finding if they have a pattern, then modifying that pattern by adding to what already exists, to do this I need the actual string)

Dir["*"].each do |tFile|
  file = File.open(tFile, "rb")
  contents = file.read
  imageLine=/<img class="myclass"(.*)\/>/
  if(contents=~imageLine)
      puts contents.sub!(imageLine, "some string"+imageLine+"some other string")
  end
end

Upvotes: 0

Views: 104

Answers (2)

tadman
tadman

Reputation: 211540

You're using sub! which is the in-place modifier version. While this has its uses, the result of the method is not the string but an indication if anything was done or not.

The sub method is more appropriate for this case. If you have multiple matches that have to be replaced, use gsub.

When doing substitution you can either use the placeholders like \1 to work with captured parts, where you capture using brackets in your regular expression, or the employ the block version to do more arbitrary manipulation.

IMAGE_REGEXP = /<img class="myclass"(.*)\/>/

Dir["*"].each do |tFile|
  File.open(tFile, "rb") do |in|
    puts in.read.gsub(IMAGE_REGEXP) { |s| "some string#{s}some other string" }
  end
end

Upvotes: 0

Michael Kohl
Michael Kohl

Reputation: 66837

You can use sub or gsub with capture groups:

"foo".gsub(/(o)/, '\1x')
=> "foxox"

For more information, consult the docs.

Upvotes: 1

Related Questions