C
Carlos Ortega
Hi,
I have some questions related the correct meaning of * + and ? in Regex
that I would appreciate some clarification:
I have an example (derived from the Programming Ruby 2nd Edition), that
I don't understand why gives these results, here is the code:
def show_regexp(a, re)
if a =~ re
puts "#{$`}<<#{$&}>>#{$'}"
else
puts "no match"
end
end
show_regexp('Example1', /\s*/)
show_regexp('Example2', /\s.*/)
show_regexp('Example3 ', /\s.?/) # Space at the end of string
show_regexp('Example4 ', /\s.+/) # Space at the end of string
show_regexp('Example5 ', /\s.*/) # Space at the end of string
output gives:
<<>>Example1
no match
Example3<< >>
no match
Example5<< >>
If I understand well:
* means - match zero or more occurrences of preceding expression.
+ means - match 1 or more occurrences of preceding expression.
? means - match 0 or 1 occurrence of preceding expression.
Why Example2 gives "no match"? I understand this as find "0 or more
occurrences" of (a space followed by any character)
Why Example4 gives "no match"? I understand this as find "1 or more
occurrence" of (a space followed by any character)
I am assuming that the null character can be matched by a .
Am I correct?
Best Regards
I have some questions related the correct meaning of * + and ? in Regex
that I would appreciate some clarification:
I have an example (derived from the Programming Ruby 2nd Edition), that
I don't understand why gives these results, here is the code:
def show_regexp(a, re)
if a =~ re
puts "#{$`}<<#{$&}>>#{$'}"
else
puts "no match"
end
end
show_regexp('Example1', /\s*/)
show_regexp('Example2', /\s.*/)
show_regexp('Example3 ', /\s.?/) # Space at the end of string
show_regexp('Example4 ', /\s.+/) # Space at the end of string
show_regexp('Example5 ', /\s.*/) # Space at the end of string
output gives:
<<>>Example1
no match
Example3<< >>
no match
Example5<< >>
If I understand well:
* means - match zero or more occurrences of preceding expression.
+ means - match 1 or more occurrences of preceding expression.
? means - match 0 or 1 occurrence of preceding expression.
Why Example2 gives "no match"? I understand this as find "0 or more
occurrences" of (a space followed by any character)
Why Example4 gives "no match"? I understand this as find "1 or more
occurrence" of (a space followed by any character)
I am assuming that the null character can be matched by a .
Am I correct?
Best Regards