DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Matching The Beginning And Ending Of A String

04.21.2010
| 3955 views |
  • submit to reddit
        Source: <a href="http://phrogz.net/programmingruby/language.html">The Ruby Language @ Programming Ruby</a> [phrogz.net]
<snip>
<pre>
\A
    Matches the beginning of the string.
\z
    Matches the end of the string.
\Z
    Matches the end of the string unless the string ends with a “\n”, in which case it matches just before the “\n”.
</pre>
</snip>

s = "Coderpath is a weekly podcast\n by Ruby developers"

s[/\A/]
=> ""

s[/[\A]+/]
=> nil

s[/.*\A/]
=> ""

s[/*\A/]
SyntaxError: (irb):10: target of repeat operator is not specified: /*\A/
   from /usr/bin/irb1.9.1:12:in `<main>'

s[/\w+\A/]
=> nil

s[/\A./]
=> "C"

s[/\A\w+/]
=> "Coderpath"

s.scan(/\A./)
=> ["C"]

s[/.*\z/]
=> " by Ruby developers"

s[/.*$/]
=> "Coderpath is a weekly podcast"

s[/.*\Z/]
=> " by Ruby developers"

s[/[^\Z]+/]
=> "Coderpath is a weekly podcast\n by Ruby developers"

s[/[^\z]+/]
=> "Coderpath is a weekly podcast\n by Ruby developers"

s[/\z/]
=> ""

s[/.\z/]
=> "s"