/as$/ means "match 'a' then 's' then end-of-line". But there is a
semicolon after the 's' in the source string, so the match fails.
puts show_regexp("abc as;",/\zas/)
\z matches end of string, and you've asked to match characters beyond
the end of string!
Your other cases are just variants of this.
Try matching with /as;$/ or /as;\z/
[There are subtle differences. \z matches only the end of the string. \Z
matches end of string or a newline character at the end of the string. $
matches end of string or a newline anywhere within the string]
Also, don't bother with a show_regexp function while you're working this
out. Just use irb to try it out interactively.
$ irb --simple-prompt
src = "abc as;"
=> "abc as;"
src =~ /as$/
=> nil
src =~ /as;$/
=> 4
[$`, $&, $']
=> ["abc ", "as;", ""]
nil means no match, 4 means matched at position 4 (counting 0 as the
first character of the string)
Thank you,Steel Steel,But why cannot use regexpresion?
then do this
f = File.open(filename)
f.each do|line|
puts line
puts "found ;" if line[-1]==";"
end
yes you can use regexp. But your requirement is simple. So simple string
indexing does the job. by the way, the reason why it did not work for
you is that you have a newline character when a line is read. So just
chomp it off
f = File.open(filename)
f.each do|line|
line.chomp!
puts "found ;" if line[-1]==";"
end
same to your regexp method
f = File.open(filename)
f.each do|line|
puts line
line.chomp!
puts line.match( %r{;$})
puts line.match( %r{;\z})
puts line.match( %r{(.*);$})
puts line.match( %r{(.*);\Z})
end