简体   繁体   中英

Ruby regex matching multiple groups with absences

I am working on ruby and git, I am trying to count the number of lines inserted and deleted in the history. I wrote the following code but I think there would be a better regex to deal with:

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

Is there a way to capture groups and absence of a group in the same group result?

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

You can write special methods for extract changed files, insertions and deletions:

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}"

This is should simplify your code and make it more clear.

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