Last active
January 29, 2021 13:23
-
-
Save tlwr/6c5c90f1a9060274e9379db51d7a6d78 to your computer and use it in GitHub Desktop.
Regular expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# if a character is followed by itself 1 or more times it is considered a duplicate | |
# | |
# the regular expression /(?<ct>(?<c>.)\k<c>{1,})|((?<d>.)\k<d>{0})/ | |
# * capture group c captures a character | |
# * capture group ct captures the total string of duplicately matched charactesr | |
# * capture group d matches a character on its own | |
# | |
# scan therefore produces the following | |
# => [["aaa", "a", nil], [nil, nil, "b"], ["ccc", "c", nil]] | |
# | |
# which we can then combine into a compressed string using map | |
# => "a3bc3" | |
"aaabccc" | |
.scan(/(?<ct>(?<c>.)\k<c>{1,})|((?<d>.)\k<d>{0})/) | |
.map { |dups, dup, single| dups.nil? ? single : "#{dup}#{dups.length}" } | |
.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment