![]() |
VOOZH | about |
A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing. Ruby regex can be used to validate an email address and an IP address too. Ruby regex expressions are declared between two forward slashes.
Syntax:
# finding the word 'hi'
"Hi there, i am using gfg" =~ /hi/ This will return the index of first occurrence of the word 'hi' if present, or else will return ' nil '.
We can also check if a string has a regex or not by using the match method. Below is the example to understand.
Example :
Output:
matchWe can use a character class which lets us define a range of characters for the match. For example, if we want to search for vowel, we can use [aeiou] for match.
Example :
Output:
1There are different short expressions for specifying character ranges :
Example :
Output:
match found
not found
match found
For matching multiple characters we can use modifiers: