
# like 999.999.999.999, but in this case we just care about the format. We can combine everything we learned so far to create more complex regular expressions.Įxample: Does this look like an IP address? # Note that this will also match some invalid IP address To match multiple characters we can use pattern modifiers. Up until now we have only been able to match a single character at a time. # In this case only the literal dot matches

then you will have to escape it.Įxample: Escaping special characters # If we don't escape, the letter will match There is also the negative form of these:

Regex match string how to#
This will not take into account the amount of characters, we will see how to do that soon. For example, matches any vowel.Įxample: Does the string contain a vowel? def contains_vowel(str) Character ClassesĪ character class lets you define a range or a list of characters to match. You are going to learn how to build more advanced patterns so you can match, capture & replace things like dates, phone numbers, emails, URLs, etc. If we don’t care about the index we could use the String#include? method.Īnother way to check if a string matches a regex is to use the match method: if "Do you like cats?".match(/like/) This returns the index of the first occurrence of the word if it was found (successful match) or nil otherwise. The most simple expressions match a word or even a single letter. Ruby regular expressions are defined between two forward slashes to differentiate them from other language syntax. In other words, your program will be able to tell the difference between a valid & invalid email address.

Think about an email address, with a ruby regex you can define what a valid email address looks like. Two common use cases for regular expressions include validation & parsing. Ruby regular expressions ( ruby regex for short) help you find specific patterns inside strings, with the intent of extracting data for further processing.
