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

Special Characters & Escape Sequences

By

Aside from the basic regular expression operators such as groupings and quantifiers, there are some other special characters and escape sequences (backslash followed by a character) that can help you out when you're working with Ruby.

There are many characters in regular expressions that are "special." Being special means the character has some meaning to the regular expression engine other than simply the character it represents. For example, the parentheses ( ) are used to create grouping and brackets [ ] are used to create character classes. But what if you want to match text that contains these characters?

You can do this by escaping them. To "escape" a character is to take away its special meaning and is accomplished by putting a backslash before it. Putting a backslash before any character that has special meaning (such as the parentheses and brackets discussed above) will remove that meaning and the character will represent itself as an element.

In this example, assume you want to match a word surrounded by parentheses. The parentheses are escaped, so they lose their special meaning. If they were not escaped, this regular expression would match any word and store that word in the capture group.

 #!/usr/bin/env ruby
 
 text = "(word)"
 puts text.sub( /\(\w+\)/, "X" )
 

Note that the backslash can not only take away special meaning to characters that have special meaning, but can also add special meaning to characters that have no special meaning in the first place. The \w escape sequence was used here, which means "word characters." The rule of thumb is that any symbol most likely has special meaning, and any simple character (like letters or numbers) don't.

  1. About.com
  2. Technology
  3. Ruby
  4. Regular Expressions
  5. Special Characters & Escape Sequences

©2014 About.com. All rights reserved.