I'm not sure if my brain is worn out or if I'm just thinking about this too hard. The following code is from the about_regular_expressions in the Ruby Koans.
def test_asterisk_means_zero_or_more assert_equal "abb", "abbcccddddeeeee"[/ab*/] assert_equal "a", "abbcccddddeeeee"[/az*/] assert_equal "", "abbcccddddeeeee"[/z*/] # THINK ABOUT IT: # # When would * fail to match? end How do you get * to fail a match?
When I say fail, I'm assuming they mean they want assert_equal to return nil. I know one way would be to throw a \ in front of the * to make the regex explicitly look for the * character but I'm pretty sure this isn't what they were implying.
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
. means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
The asterisk is known as a repeater symbol, meaning the preceding character can be found 0 or more times. For example, the regular expression ca*t will match the strings ct, cat, caat, caaat, etc.
Maybe the answer to "when would * fail to match" is "never".
Since * will always accept the empty string, it will only fail if you have something before or after it that doesn't match. For example, ab*c will fail to match azc, since b* will not match z and c will not match zc.
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