Ruby 如何搜索两个或多个空格和指针

Ruby 如何搜索两个或多个空格和指针,ruby,string,Ruby,String,我试图读取一个.txt文件,在每行中搜索两个或更多的空白,并使用stringScanner gem将指针保存在匹配的位置 到目前为止,我已经设法找到了匹配项,但我不知道如何保存指针 require 'strscan' class LintFile attr_reader :file, :lines def initialize(filepath) @file = File.open(filepath) @lines = [] end def read

我试图读取一个.txt文件,在每行中搜索两个或更多的空白,并使用stringScanner gem将指针保存在匹配的位置

到目前为止,我已经设法找到了匹配项,但我不知道如何保存指针

require 'strscan'

class LintFile
  attr_reader :file, :lines
  def initialize(filepath)
    @file = File.open(filepath)
    @lines = []
  end

  def read
    # Here I get each line into an array
    @file.each_with_index do |line, ind|
       @lines[ind] = StringScanner.new(line)
    end
  end
end

def check_error(filepath)
    @file_to_check = LintFile.new(filepath)
    @file_to_check.read
    #file_to_check.lines
  
    #Scan each line
    @file_to_check.lines.length.times do |line|
      whitespace(line)
    end
end

def whitespace(line)
  if @file_to_check.lines[line].string.match?("  ")
    #pos is not giving the pointer where the match occurred
    pointer = @file_to_check.lines[line].pos
    puts "Estoy dentro del unless #{pointer}"
  end
end
请帮帮我


提前感谢

假设文件包含读取到变量
str
中的字符串。例如:

str =<<~_
Now is  the time for
all good Rubyists to
come    to the    aid
of their fellow    coders.
_
我们获得:

arr = scan_it(str)
  #=> [6, 46, 56, 79] 
让我们检查一下
str
中这些偏移量周围的子字符串

arr.map { |n| puts str[n-3,10] }
 is  the t
ome    to 
the    aid
low    cod
正则表达式
/{2,}/
匹配两个或多个空格。正则表达式
/?[^]+/
匹配一个或多个(
+
)字符,而不是空格(
[^]
),可以选择前面加一个空格(

下表显示了
s.scan
的匹配项。(第一列中的下划线表示空格。)

获取每条线的偏移量

str.each_line.with_index.with_object({}) do |(line,i),h|
  h[i] = scan_it(line)
end
  #=> {0=>[6], 1=>[], 2=>[4, 14], 3=>[15]}
这表明在第一行(行偏移量
0
),从偏移量
6
开始,有两个或两个以上空格的子字符串,第二行没有子字符串,第三行有两个,从偏移量
4
14
开始,最后一行有一个,从偏移量
15
开始

看,还有

使用

这里有一种更简单的方法来计算不使用
StringScanner
的所需偏移量

str.gsub(/ {2,}/).map { |_,arr| Regexp.last_match.begin(0) }
  #=> [6, 46, 56, 79]
这使用了
String#gsub
的形式,它只接受一个参数(模式)而不接受任何块。这将返回一个枚举数,该枚举数只生成匹配项(每个匹配项包含两个或多个空格的字符串),并且不执行替换(使名称
gsub
有些混乱)。我已经把统计员拴在了墙上

每个匹配由第一个块变量保存。我已经为该变量使用了下划线,以向读者发出信号,表明它未用于块计算(一种常见做法)

另请参见,它返回一个
MatchData
对象,并提供当前匹配开始的偏移量

获取两个或多个空格开始的子字符串行中的行和位置

str.each_line.with_index.with_object({}) do |(line,i),h|
  h[i] = line.gsub(/ {2,}/).map { |_,arr| Regexp.last_match.begin(0) }
end
  #=> {0=>[6], 1=>[], 2=>[4, 14], 3=>[15]}
谢谢字符串#子描述为我节省了数小时的研究时间!
str.gsub(/ {2,}/).map { |_,arr| Regexp.last_match.begin(0) }
  #=> [6, 46, 56, 79]
str.each_line.with_index.with_object({}) do |(line,i),h|
  h[i] = line.gsub(/ {2,}/).map { |_,arr| Regexp.last_match.begin(0) }
end
  #=> {0=>[6], 1=>[], 2=>[4, 14], 3=>[15]}