1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Endless Strings? The Beginning of the End

Special Syntax and Strings


Without special syntax, there is no way to describe the beginning or end of a string in Ruby. The beginning and end are not characters, so they don't follow the normal rules for regular expression elements.

^ and \A

The beginning of a string can be matched with the ^ character or with the \A escape sequence. The next element in the regex must be the first character in the string. Obviously this only makes sense as the first character in a regex, as there can be no characters before the beginning of a string.

$ and \z

The end of a string can be matched with the $ or \z. No elements can follow this character. Again, just as it wouldn't make sense to have a character before the beginning, it would make no sense for characters to be after the end of the string. The element directly preceding this "end of string" marker must be the last character in the string.

An Optional Escape Sequence

Optionally, you can use the \Z escape sequence (note the upper-case Z). This has a slightly different meaning. Instead of just the end of the string, it will also match a newline directly before the end of the string. This allows your regular expression to work on both "chomped" and "unchomped" strings.

This example will match a word in parentheses if it's the only thing in the string. It's also a good example of "symbol soup" and is one of the reasons regular expressions can be so intimidating. Just read from left to right and pay attention to backslashes. This is a small regular expression as well, complex regular expressions can often be 40 characters or more of symbol soup; it just takes some practice to be able to read.

 #!/usr/bin/env ruby
 text1 = "(foo)"
 text2 = "foo (bar) baz"
 puts text1.sub( /\(\w+\)/, "X" )
 puts text2.sub( /\(\w+\)/, "X" )
 puts text1.sub( /^\(\w+\)$/, "X" )
 puts text2.sub( /^\(\w+\)$/, "X" )
  1. About.com
  2. Technology
  3. Ruby
  4. Regular Expressions
  5. Endless Strings? The Beginning of the End

©2014 About.com. All rights reserved.