Regular expressions are an important component of any programming language, not just Ruby. Without the use of regular expressions (or regex or regexen) it can be very difficult to recognize strings, group or quantify objects or otherwise describe patterns in your code. Getting started with regular expressions in Ruby simply requires understanding how regexen are used and their characters and syntax.
strings to text. More simply, they're a way to describe the format and structure of strings. They are used in a variety of methods to extract or replace portions of a string.
Unfortunately, regexen can be cryptic and sometimes outright unreadable. They are composed of two types of things: elements and operators. Though there are many operators, operators known as quantifiers are the most commonly used and, though at first they may seem difficult, the terse and cryptic syntax allows you to create powerful regexen quickly and in a compact form.
Some of the most powerful and useful operators in the Ruby regex syntax are the grouping operators. While quantifiers only work on the previous element, the grouping operators allow you to group multiple elements together into a single element.
Quantifiers tell how many times an element should be matched.Though in Ruby you can get by with the common quantifiers such as + or ?, there are at least four more you should know about.
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?
Other Things You Need to Know About Regular Expressions
- Handy Shortcuts: A List of Commonly Used Named Character Classes:
10 frequently used "shortcuts" for commonly seen sets (or classes) of characters.
- Regular Expression Options:
In addition to the regular expression language features in Ruby, there are also four options that may be appended to regular expression literals that will change how the regular expression acts. While some of these are not frequently used, they can help you in some tricky situations.
- Lookahead and Back-references:
Ruby's regular expression language allows you to match previous groupings and look ahead in the character stream without actually consuming these characters. These mechanisms allow you to create regular expressions that make sense in context with what's around it.
- Special Syntax and Strings in Regular Expressions:
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.