简体   繁体   中英

Parsing a directory of files with regex and ruby

I'm trying to do a simple regex to grab specific text out of a bunch of text files in a directory. The code I'm using is below:

input_dir = File.join('path/to/file/dir/', "*.txt")

Dir.glob(input_dir) do |file|
  if /\.txt$/i.match file
    File.open(file, "r") do |_file|
      /==BEGIN==(.*)==END==/.match _file.read
      puts $1
    end
  end
end

That works for exactly 1 of the files in the directory, but all other files return nil. Am I missing something here?

Hard to guess with so little data, but could it be that in most files (except one), ==BEGIN== and ==END== are on different lines?

Does /==BEGIN==(.*)==END==/m.match _file.read change anything? The /m modifier allows the dot to also match newlines in Ruby.

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