will match from the beginning of any lines within the string."
The ^ anchors the regular expression to the beginning of the line. In
the above example there are three lines. You can see where they are
by this example which replaces the “nothing” at the beginning of every
line with an ‘X’ character.
puts x.gsub(/^/, ‘X’)
XWe like Ruby
XThey adore Ruby
XEveryone loves Ruby
The location of the 'X’s mark the beginning of the lines.
More rigoriously a line begins at the beginning or after any newline
character.
I’m also having a bit of trouble using the syntax \A and \Z. Can
anybody show how it’s done please?
The \A matches only at the beginning of the string. This ignores
embedded newlines.
puts x.gsub(/\A/, ‘X’)
XWe like Ruby
They adore Ruby
Everyone loves Ruby
The \Z matches only at the end of the string, or before a newline at
the end. This is unfortunately inconsistent because it will match
twice at the end if there is a newline at the end.
puts x.gsub(/\Z/, ‘X’)
We like Ruby
They adore Ruby
Everyone loves RubyX
X
This is unfortunate but compatible with PCRE (perl compatible regular
expression). If the ending newline is stripped off then this matches
only at the end.
puts x.strip.gsub(/\Z/, ‘X’)
We like Ruby
They adore Ruby
Everyone loves RubyX
Bob
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.