Skip to content

Instantly share code, notes, and snippets.

@mernen
Last active March 28, 2021 13:42
Show Gist options
  • Save mernen/5846258 to your computer and use it in GitHub Desktop.
Save mernen/5846258 to your computer and use it in GitHub Desktop.
FizzBuzz as a Regexp - source for http://pastie.org/158799
#! /usr/bin/env ruby1.9
puts 1.upto(100).to_a.join("\n").
gsub(%r{
(?# matchers for multiples of 3 -- remainder=0,1,2 respectively)
(?<z>[0369]+(?:\g<u>\g<d>|\g<d>\g<u>)?|\g<u>\g<d>|\g<d>\g<u>){0}
(?<u>[147]\g<z>?|[258][0369]*\g<d>){0}
(?<d>[258]\g<z>?|[147][0369]*\g<u>){0}
(?# fizz/buzz matchers)
(?<fizz>\g<z>){0}
(?<buzz>\d*[05]){0}
(?<fizzbuzz>\g<z>?0|[0369]*\g<u>5){0}
(?# we must test for fizzbuzz first)
(?<!\d)(?:\g<fizzbuzz>|\g<buzz>|\g<fizz>)(?!\d)
}x) {
case
when $4; "Fizz"
when $5; "Buzz"
when $6; "FizzBuzz"
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment