简体   繁体   中英

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

You can use sub or gsub with capture groups:

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

For more information, consult the docs .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM