Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regexp returning "" vs nil

Tags:

regex

ruby

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
like image 1000
H.Rabiee Avatar asked Aug 27 '13 10:08

H.Rabiee


People also ask

What does =~ mean in Ruby regex?

=~ 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.

What kind of regex does Ruby use?

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.


1 Answers

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.

like image 159
Marcelo De Polli Avatar answered Oct 07 '22 01:10

Marcelo De Polli