Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform subtraction within regular expression

Tags:

regex

ruby

I have the following RSpec output:

30 examples, 15 failures

I would like to subtract the second number from the first. I have this code:

def capture_passing_score(output)
  captures = output.match(/^(?<total>\d+)\s*examples,\s*(?<failed>\d+)\s*failures$/)
  captures[:total].to_i - captures[:failed].to_i
end

I am wondering if there is a way to do the calculation within a regular expression. Ideally, I'd avoid the second step in my code, and subtract the numbers within a regex. Performing mathematical operations may not be possible with Ruby's (or any) regex engine, but I couldn't find an answer either way. Is this possible?

like image 698
David W Avatar asked Feb 25 '26 06:02

David W


1 Answers

Nope.

By every definition I have ever seen, Regular Expressions are about text processing. It is character based pattern matching. Numbers are a class of textual characters in Regex and do not represent their numerical values. While syntactic sugar may mask what is actually being done, you still need to convert the text to a numeric value to perform the subtraction.

WikiPedia

RubyDoc

like image 137
virullius Avatar answered Feb 26 '26 23:02

virullius