红宝石中的正则表达式匹配,检查空白区域

时间:2014-08-07 14:30:32

标签: ruby regex whitespace

我正在尝试在每行的开头检查文件是否有空格。我希望行首的空白区域保持一致,所有空格都以空格开头或者全部以制表符开头。我写了下面的代码,但它并不适合我。如果在一行的开头存在空格,然后在另一行的开头存在制表符,则打印警告或其他内容。

    file = File.open("file_tobe_checked","r")  #I'm opening the file to be checked 

    while (line = file.gets)

    a=(line =~ /^ /).nil?  
    b=(line =~/^\t/).nil?

    if  a==false && b==false
    print "The white spaces at the beginning of each line are not consistent"
    end 

    end
    file.close

3 个答案:

答案 0 :(得分:1)

这是一个解决方案,您不会读取文件或提取的行数组两次:

#!/usr/bin/env ruby
file = ARGV.shift
tabs = spaces = false
File.readlines(file).each do |line|
  line =~ /^\t/ and tabs = true
  line =~ /^ / and spaces = true
  if spaces and tabs
    puts "The white spaces at the beginning of each line are not consistent."
    break
  end
end

用法:

ruby script.rb file_to_be_checked

将线与这些线进行比较可能更有效:

  line[0] == "\t" and tabs = true
  line[0] == ' ' and spaces = true

您还可以使用each_line而不是readlines。也许each_line允许您逐行读取文件,而不是一次性读取所有行:

File.open(file).each_line do |line|

答案 1 :(得分:0)

检查空格(并相应地发出警告/通知)有多重要?如果您的目标只是纠正空白,.strip非常适合处理错误的空白。

 lines_array = File.readlines(file_to_be_checked)

 File.open(file_to_be_checked, "w") do |f|
    lines_array.each do |line|
      # Modify the line as you need and write the result
      f.write(line.strip)
    end
 end

答案 2 :(得分:0)

我假设没有一行可以以一个或多个空格开头,后跟一个标签,反之亦然。

仅仅断定文件中存在一个或多个不一致对处理问题没有多大帮助。相反,您可以考虑给出以空格或制表符开头的第一行的行号,然后给出以空格或制表符开头的所有后续行的行号,该行号或制表符与找到的第一行不匹配。你可以这样做(抱歉,未经测试)。

def check_file(fname)
  file = File.open(fname,"r") 
  line_no = 0
  until file.eof?
    first_white = file.gets[/(^\s)/,1]
    break if first_white
    line_no += 1
  end
  unless file.eof?
    puts "Line #{line_no} begins with a #{(first_white=='\t') ? "tab":"space"}"    
    until file.eof?
      preface = file.gets[/(^\s)/,1))]
      puts "Line #{line_no} begins with a #{(preface=='\t') ? "tab":"space"}" \
        if preface && preface != first_white
      line_no += 1
    end
  end
  file.close
end