0

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
2
  • I think you need to open the File with write permissions, File.open(tFile, 'rw') and iterate each line of the file, replacing the line where you find the pattern. Commented Aug 2, 2012 at 14:23
  • You open with write if you're writing to it. Here the puts is going to STDOUT. Commented Aug 2, 2012 at 14:49

2 Answers 2

1

You can use sub or gsub with capture groups:

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

For more information, consult the docs.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.