Skip to content

Instantly share code, notes, and snippets.

@Oceantidote
Created January 18, 2021 11:18
Show Gist options
  • Save Oceantidote/2d7c8519f136d4f7861320274cdb1da7 to your computer and use it in GitHub Desktop.
Save Oceantidote/2d7c8519f136d4f7861320274cdb1da7 to your computer and use it in GitHub Desktop.
# Phone regex with if/else
phone_number = "+44 76 4775 4789"
if phone_number.match?(/^\+\d{2}\s\d{2}\s\d{4}\s\d{4}$/)
puts "This is a valid UK international phone number"
else
puts "It's not valid!"
end
# Better phone regex allowing for optional spaces
if phone_number.match?(/^\+\d{2}\s*\d{2}\s*\d{4}\s*\d{4}$/)
puts "This is a valid UK international phone number"
else
puts "It's not valid!"
end
# Simple regex with ternary operator
input = "hi my name is lenny"
puts input =~ /is/ ? "hello" : "goodbye"
# Multi line regex with the multi-line modifier
text = "try this is a multi-line text line
to match only this
try and not the others"
# End and beginning of line match
puts text =~ /^try .* line$/m
# End and beginning of entire string match
puts text =~ /\Atry .* line\z/m
# Multiple group regex
match_data = "John Doe Watkins".match(/^(\w+) (\w+) (\w+)$/)
p match_data
puts match_data[0]
puts "#{match_data[1]}"
puts "#{match_data[2]}"
puts "#{match_data[3]}"
# Multiple named group regex
pattern = /^(?<first_name>\w+) (?<last_name>\w+)$/
match_data = "John Doe".match(pattern)
p match_data
puts match_data[:first_name]
puts match_data[:last_name]
# Gsub with a regex
puts "hello guys".gsub("hello", "goodbye")
puts "hello guys".gsub(/g\w{3}/, 'le wagon')
puts "hello g&%$".gsub(/g.{3}/, 'le wagon')
puts "hello guys".gsub(/^(\w+) (\w+)$/, 'Oh \2, \1!')
puts "hello guys yay".gsub(/^(\w+) (\w+) (\w+)$/, 'Oh \1, \2 hey\3!')
# Destructive gsub with a regex
string = "hello guys yay"
puts string
puts string.gsub!(/^(\w+) (\w+) (\w+)$/, 'Oh \1, \2 hey\3!')
puts string
# Original scan to return an array of matches
p "Let's play tic tac toe".scan(/t../)
# Improved scan to return of individual words
p "Let's play tic tac toe".scan(/\bt..\b/)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment