What is the reason behind different results between the following regexp statements:
"abbcccddddeeee"[/z*/] # => ""
And these that return nil
:
"some matching content"[/missing/] # => nil
"start end"[/\Aend/] # => nil
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
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.
What's happening is that /z*/
will return zero or more occurrences of z
.
If you use /z+/
, which returns one or more, you'll see it returns nil
as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With