Thursday, July 26, 2012

Ruby Regex Syntax

Regular-expression modifiers:

Regular expression literals may include an optional modifier to control various aspects of matching. The modifier is specified after the second slash character, as shown previously and may be represented by one of these characters:

ModifierDescription
iIgnore case when matching text.
oPerform #{} interpolations only once, the first time the regexp literal is evaluated.
xIgnores whitespace and allows comments in regular expressions
mMatches multiple lines, recognizing newlines as normal characters
u,e,s,nInterpret the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding.

Like string literals delimited with %Q, Ruby allows you to begin your regular expressions with %r followed by a delimiter of your choice. This is useful when the pattern you are describing contains a lot of forward slash characters that you don't want to escape:

# Following matches a single slash character, no escape required
%r|/|               

# Flag characters are allowed with this syntax, too
%r[</(.*)>]i  

Regular-expression patterns:

Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash.

Following table lists the regular expression syntax that is available in Ruby.

PatternDescription
^Matches beginning of line.
$Matches end of line.
.Matches any single character except newline. Using m option allows it to match newline as well.
[...]Matches any single character in brackets.
[^...]Matches any single character not in brackets
re*Matches 0 or more occurrences of preceding expression.
re+Matches 1 or more occurrence of preceding expression.
re?Matches 0 or 1 occurrence of preceding expression.
re{ n}Matches exactly n number of occurrences of preceding expression.
re{ n,}Matches n or more occurrences of preceding expression.
re{ n, m}Matches at least n and at most m occurrences of preceding expression.
a| bMatches either a or b.
(re)Groups regular expressions and remembers matched text.
(?imx)Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?-imx)Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?: re)Groups regular expressions without remembering matched text.
(?imx: re)Temporarily toggles on i, m, or x options within parentheses.
(?-imx: re)Temporarily toggles off i, m, or x options within parentheses.
(?#...)Comment.
(?= re)Specifies position using a pattern. Doesn't have a range.
(?! re)Specifies position using pattern negation. Doesn't have a range.
(?> re)Matches independent pattern without backtracking.
\wMatches word characters.
\WMatches nonword characters.
\sMatches whitespace. Equivalent to [\t\n\r\f].
\SMatches nonwhitespace.
\dMatches digits. Equivalent to [0-9].
\DMatches nondigits.
\AMatches beginning of string.
\ZMatches end of string. If a newline exists, it matches just before newline.
\zMatches end of string.
\GMatches point where last match finished.
\bMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\BMatches nonword boundaries.
\n, \t, etc.Matches newlines, carriage returns, tabs, etc.
\1...\9Matches nth grouped subexpression.
\10Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.

Regular-expression Examples:

Literal characters:

ExampleDescription
/ruby/Match "ruby".
¥Matches Yen sign. Multibyte characters are suported in Ruby 1.9 and Ruby 1.8.

Character classes:

ExampleDescription
/[Rr]uby/ Match "Ruby" or "ruby"
/rub[ye]/ Match "ruby" or "rube"
/[aeiou]/Match any one lowercase vowel
/[0-9]/ Match any digit; same as /[0123456789]/
/[a-z]/Match any lowercase ASCII letter
/[A-Z]/Match any uppercase ASCII letter
/[a-zA-Z0-9]/Match any of the above
/[^aeiou]/ Match anything other than a lowercase vowel
/[^0-9]/Match anything other than a digit

Special Character Classes:

ExampleDescription
/./ Match any character except newline
/./m In multiline mode . matches newline, too
/\d/Match a digit: /[0-9]/
/\D/ Match a nondigit: /[^0-9]/
/\s/Match a whitespace character: /[ \t\r\n\f]/
/\S/ Match nonwhitespace: /[^ \t\r\n\f]/
/\w/ Match a single word character: /[A-Za-z0-9_]/
/\W/Match a nonword character: /[^A-Za-z0-9_]/

Repetition Cases:

ExampleDescription
/ruby?/ Match "rub" or "ruby": the y is optional
/ruby*/ Match "rub" plus 0 or more ys
/ruby+/Match "rub" plus 1 or more ys
/\d{3}/Match exactly 3 digits
/\d{3,}/Match 3 or more digits
/\d{3,5}/Match 3, 4, or 5 digits

Nongreedy repetition:

This matches the smallest number of repetitions:

ExampleDescription
/<.*>/Greedy repetition: matches "<ruby>perl>"
/<.*?>/ Nongreedy: matches "<ruby>" in "<ruby>perl>"

Grouping with parentheses:

ExampleDescription
/\D\d+/ No group: + repeats \d
/(\D\d)+/ Grouped: + repeats \D\d pair
/([Rr]uby(, )?)+/Match "Ruby", "Ruby, ruby, ruby", etc.

Backreferences:

This matches a previously matched group again:

ExampleDescription
/([Rr])uby&\1ails/Match ruby&rails or Ruby&Rails
/(['"])(?:(?!\1).)*\1/Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc.

Alternatives:

ExampleDescription
/ruby|rube/Match "ruby" or "rube"
/rub(y|le))/Match "ruby" or "ruble"
/ruby(!+|\?)/ "ruby" followed by one or more ! or one ?

Anchors:

This need to specify match position

ExampleDescription
/^Ruby/Match "Ruby" at the start of a string or internal line
/Ruby$/ Match "Ruby" at the end of a string or line
/\ARuby/ Match "Ruby" at the start of a string
/Ruby\Z/Match "Ruby" at the end of a string
/\bRuby\b/Match "Ruby" at a word boundary
/\brub\B/\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
/Ruby(?=!)/Match "Ruby", if followed by an exclamation point
/Ruby(?!!)/ Match "Ruby", if not followed by an exclamation point

Special syntax with parentheses:

ExampleDescription
/R(?#comment)/ Matches "R". All the rest is a comment
/R(?i)uby/ Case-insensitive while matching "uby"
/R(?i:uby)/ Same as above
/rub(?:y|le))/Group only without creating \1 backreference
http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm -------------------------------------------------------------------------------------------------------------- Disclaimer: I cannot assume any liability for the content of external pages. Solely the operators of those linked pages are responsible for their content. I make every reasonable effort to ensure that the content of this Web site is kept up to date, and that it is accurate and complete. Nevertheless, the possibility of errors cannot be entirely ruled out. I do not give any warranty in respect of the timeliness, accuracy or completeness of material published on this Web site, and disclaim all liability for (material or non-material) loss or damage incurred by third parties arising from the use of content obtained from the Web site. Registered trademarks and proprietary names, and copyrighted text and images, are not generally indicated as such on my Web pages. But the absence of such indications in no way implies the these names, images or text belong to the public domain in the context of trademark or copyright law. All product and firm names on www.erco.com are proprietary names of their corresponding owners All products and firm names used in this site are proprietary names of their corresponding owners. All rights are reserved which are not explicitly granted here.