A Simple question on regular expression in ruby. Some can make me
understand the below code snippets. I was under the impression that
both these statement would give the same answer. But it doesnt. Why ?
In this case you are looking for '', 'an', 'anan', 'ananan' and so on.
So it matches at the beginning of the string (index 0) with the empty
string.
Luis
···
On 1/10/07, Manoj P M <manjo.pm@gmail.com> wrote:
A Simple question on regular expression in ruby. Some can make me
understand the below code snippets. I was under the impression that
both these statement would give the same answer. But it doesnt. Why ?
A Simple question on regular expression in ruby. Some can make me
understand the below code snippets. I was under the impression that
both these statement would give the same answer. But it doesnt. Why ?
irb(main):001:0> 'banana' =~ /(an)*/
=> 0
this is happening because * means 0 or more times match the preceding
literal. here always the regex match =~ returns the position in the string
where it finds the match and starts from 0 (as in C and ruby the array
parameter starts count from 0 like if array='sachin' and then array[0] will
give 's')
so in the first case it matches 'b' and returns zero since it tries to match
'an' matched 0 times so returns the position taken by 'b'
irb(main):002:0> 'banana' =~ /(an)+/
=> 1
in this case the place where it matches 'an' is starting at b(0) a(1) n(2)
a(3) n(4) a(5) so returns 1 since 'an' is matched beginning at 1 location.