-2

I'm confused about why does asterisk have an impact on the regular expressions results in Ruby? Example codes are below:

2.3.0 :001 > "abbcccddddeeeee"[/z*/]
 => "" 
2.3.0 :002 > "abbcccddddeeeee"[/z/]
 => nil 

Why the first one with * returns an empty string, while the other one returns nil?

Thanks!

miken32
  • 42,008
  • 16
  • 111
  • 154
Penny
  • 1,218
  • 1
  • 13
  • 32

2 Answers2

1

* is a quantifier that means "0 or more".

Your first snippet matches 0 instance of z. Your second snippet doesn't match anything.

user229044
  • 232,980
  • 40
  • 330
  • 338
0

The Kleene star means "zero or more". In the first case, there are 0 zs in the string, which means that there is a match (actually even infinitely many matches) of "zero or more zs".

In the second case, you search for the occurrence of a single z in the string which doesn't exist.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653