Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Star Regex Operator to Fail

Tags:

regex

ruby

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.

like image 370
Ryan Castillo Avatar asked Feb 22 '11 21:02

Ryan Castillo


People also ask

What does * do in regex?

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.

What does ?= * Mean in regex?

. means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it.

What does regex 0 * 1 * 0 * 1 * Mean?

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.

What does the star mean in regex?

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.


2 Answers

Maybe the answer to "when would * fail to match" is "never".

like image 173
Andrew Grimm Avatar answered Oct 02 '22 19:10

Andrew Grimm


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.

like image 44
Jeremiah Willcock Avatar answered Oct 02 '22 19:10

Jeremiah Willcock