
A Regular Expression, or regex, or regexp, is used to match a pattern against a string. The literal constructors are /.../
and %r{...}
. The other constructor is Regexp::new
. Examples:
/dog/.match('dogwalker')
=>#<MatchData "dog">
/dog/ =~ ('cat')
=>nil
Note that we can use #match
or =~
to test if it matches. But =~
will return nil or the position in the string it finds the match.
Some characters have to be "escaped" with a backslash because they have specific meanings in a regexp. Those characters are:
{ => \{
} => \}
( => \(
) => \)
[ etc.
]
.
?
+
*
Example:
/1 \+ 2/.match('1 + 2')
=>#<MatchData "1 + 2">
You can interpolate the match criteria like so:
name = "Majd"
/#{name}/.match("Hey, Majd")
=>#<MatchData "Majd">
The following are different ways to check different criteria. Note the characters used:
/[aeiou]/ => brackets check individual
characters listed without commas
/[0-9a-d]/ => hyphen checks a range
/[^a-d]/ => caret checks if NOT in range
I think that's good for now. I haven't used these, so I don't want to add examples I don't yet understand. I may come back and add more to this, since I think it might be easier for me to read than RubyDocs (who am I kidding? RubyDocs is great!) In any event, I hope you enjoyed my little demo on RegExp.