Ruby正则表达式匹配多个缺席组

时间:2015-03-06 16:41:09

标签: ruby regex regex-group

我正在处理ruby和git,我正在尝试计算历史记录中插入和删除的行数。我写了下面的代码,但我认为有一个更好的正则表达式来处理:

a = [" 1 file changed, 2 insertions(+), 2 deletions(-)", 
 " 1 file changed, 8 insertions(+)",
 " 1 file changed, 5 deletions(-)"]

insertions = 0
deletions = 0
commits = 0
a.each do |msg|
  i1, d1, i2, d2 = msg.match(/(\d*)? insertion.*?(\d*) deletion.*|(\d*)? insertion|(\d*) deletion/).captures
  insertions += i1.to_i unless i1.nil?
  insertions += i2.to_i unless i2.nil?
  deletions += d1.to_i unless d1.nil?
  deletions += d2.to_i unless d2.nil?
  commits += 1
end

puts insertions, deletions, commits

有没有办法在相同的组结果中捕获组和缺少组?

...
i, d = msg.match(WANTED_REGEX).captures
insertions += i.to_i unless i1.nil?
insertions += d.to_i unless i2.nil?
...

1 个答案:

答案 0 :(得分:0)

您可以编写用于提取已更改文件,插入和删除的特殊方法:

lines = [
 " 1 file changed, 2 insertions(+), 2 deletions(-)", 
 " 1 file changed, 8 insertions(+)",
 " 1 file changed, 5 deletions(-)"
]

def count_changed_files(line)
  /(?<value>\d+) files? changed/ =~ line ? value.to_i : 0
end

def count_inserted_lines(line)
  /(?<value>\d+) insertions?/ =~ line ? value.to_i : 0
end

def count_deleted_lines(line)
  /(?<value>\d+) deletion?/ =~ line ? value.to_i : 0
end

total_changed_files = 0
total_insertions = 0
total_deletions = 0

lines.each do |line|
  changed_files = count_changed_files(line)
  insertions = count_inserted_lines(line)
  deletions = count_deleted_lines(line)

  total_changed_files += changed_files
  total_insertions += insertions
  total_deletions += deletions

  puts "changed: #{changed_files}, insertions: #{insertions}, deletions: #{deletions}"
end

puts "--- total ---"
puts "changed: #{total_changed_files}, insertions: #{total_insertions}, deletions: #{total_deletions}"

这应该简化您的代码并使其更清晰。