Ruby:与Regex匹配分隔符

时间:2014-02-26 22:20:59

标签: ruby regex

我正在尝试使用正则表达式模式来解决这个问题,即使我的测试通过了这个解决方案,我也希望拆分到数组中只有["1", "2"]。有没有更好的方法呢?

irb testing

 s = "//;\n1;2" # when given a delimiter of ';'

 s2 = "1,2,3" # should read between commas

 s3 = "//+\n2+2" # should read between delimiter of '+'

 s.split(/[,\n]|[^0-9]/)

 => ["", "", "", "", "1", "2"]

生产

module StringCalculator
  def self.add(input)
    solution = input.scan(/\d+/).map(&:to_i).reduce(0, :+)
    input.end_with?("\n") ? nil : solution
  end
end

测试

context 'when given a newline delimiter' do                                                                                                                          
  it 'should read between numbers' do                                                                                                                              
    expect(StringCalculator.add("1\n2,3")).to eq(6)                                                                                                                 
  end                                                                                                                                                               

  it 'should not end in a newline' do                                                                                                                               
    expect(StringCalculator.add("1,\n")).to be_nil                                                                                                                 
  end                                                                                                                                                              
end 

context 'when given different delimiter' do                                                                                                                         
  it 'should support that delimiter' do                                                                                                                           
    expect(StringCalculator.add("//;\n1;2")).to eq(3)                                                                                                             
  end                                                                                                                                                          
end 

2 个答案:

答案 0 :(得分:1)

使用String#scan非常简单:

s = "//;\n1;2"
s.scan(/\d/) # => ["1", "2"]

/\d/ - 数字字符([0-9]

注意:

如果您有如下字符串,则应使用/\d+/

s = "//;\n11;2"
s.scan(/\d+/) # => ["11", "2"]

答案 1 :(得分:1)

您的数据看起来像这个字符串://1\n212

如果您将数据作为文件获取,请将其视为两个单独的行。如果它是一个字符串,那么,再次将其视为两个单独的行。在任何一种情况下,它看起来像

//1
212
输出时

如果是字符串:

input = "//1\n212".split("\n")
delimiter = input.first[2] # => "1"
values = input.last.split(delimiter) # => ["2", "2"]

如果是文件:

line = File.foreach('foo.txt')
delimiter = line.next[2] # => "1"
values = line.next.chomp.split(delimiter) # => ["2", "2"]