Created
July 17, 2017 08:29
-
-
Save Papillard/7b992fb8e69acd5f6ac52386c991e047 to your computer and use it in GitHub Desktop.
Playing with Regexp in ruby
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
# Validate data with =~ (to check it matches a regexp) | |
welcome = "hello guys!" | |
if text =~ /l{3}/ | |
puts "This is nice welcome message" | |
end | |
email = "[email protected]" | |
if email =~ /^\w+@\w+\.\w+$/ | |
puts "Valid email" | |
else | |
puts "Invalid email" | |
end | |
# Extract data precisely with match (us groups with ()) | |
full_name = "John Doe" | |
name_match = full_name.match(/^(?<first_name>\w+) (?<last_name>\w+)$/) | |
p name_match[0] | |
p name_match[:first_name] | |
p name_match[:last_name] | |
# match returns a MatchData object | |
# It is neither an Array nor a Hash | |
# It gives you access to the different groups () matched | |
# You access them with index or with symbols if you named your groups | |
# gsub => substitution of all texts matching a regexp | |
text = "hello guys " | |
p text.gsub(/g\w{3}/, "wagon") | |
# scan => global scanning of a text (less precise than match) | |
text_with_years = "This happened in 1986 then later on in 2001 and 2003 balblabla" | |
all_years_matched = text_with_years.scan(/\d{4}/) | |
p all_years_matched |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment