Ruby Regular Expressions
Regular expressionsis a special sequence of characters that matches or finds sets of strings by using a pattern with a specialized syntax.
A regular expression uses some predefined specific characters and combinations of these characters to form a 'rule string', which expresses a filtering logic for strings.
Syntax
Regular expressionsLiterally, it is a pattern between slashes or between arbitrary delimiters following %r, as shown below:
/
pattern
/
/
pattern
/im
Options can be specified
%
r
!
/
usr
/
local
!
Regular expressions using delimiters
Example
!/usr/bin/ruby
line1
=
"
Cats are smarter than dogs
"
;
line2
=
"
Dogs also like meat
"
;
if
(
line1
=~
/
Cats(.*)
/
)
puts
"
Line1 contains Cats
"
end
if
(
line2
=~
/
Cats(.*)
/
)
puts
"
Line2 contains Dogs
"
end
Try it »
The above example produces the following output:
Line1 contains Cats
Regular expression modifiers
A regular expression may literally include an optional modifier that controls various aspects of matching. The modifier is specified after the second slash character, as shown in the example above. The table below lists the possible modifiers:
| Modifiers | Description |
|---|---|
| i | Ignores case when matching text. |
| o | Performs #{} interpolation only once; the regular expression is evaluated at the first time. |
| x | Ignores whitespace, allowing whitespace and comments throughout the expression. |
| m | Matches multiple lines, treating newline characters as normal characters. |
| u,e,s,n | Interprets the regular expression as Unicode (UTF-8), EUC, SJIS, or ASCII. If no modifier is specified, the regular expression is assumed to use the source encoding. |
Just as strings are delimited with %Q, Ruby allows you to start a regular expression with %r followed by an arbitrary delimiter. This is very useful when describing patterns containing many slash characters that you do not want to escape.
The following matches a single slash character without escaping
%
r
|
/
| # Flag characters can be matched with the following syntax %r[<
/
(
.*
)
]
i
Regular expression patterns
Except for control characters,(+ ? . * ^ $ ( ) [ ] { } | ), all other characters match themselves. You can escape a control character by placing a backslash before it.
The following table lists the regular expression syntax available in Ruby.
| Mode | Description |
|---|---|
| ^ | Matches the beginning of a line. |
| $ | Matches the end of a line. |
| . | Matches any single character except a newline. With the m option, it can also match a newline. |
| [...] | Matches any single character in the square brackets. |
| [^...] | Matches any single character not in the square brackets. |
| re* | Matches the preceding subexpression zero or more times. |
| re+ | Matches the preceding subexpression one or more times. |
| re? | Matches the preceding subexpression zero or one time. |
| re{ n} | Matches the preceding subexpression exactly n times. |
| re{ n,} | Matches the preceding subexpression n or more times. |
| re{ n, m} | Matches the preceding subexpression at least n times and at most m times. |
| a| b | Matches a or b. |
| (re) | Groups a regular expression and remembers the matched text. |
| (?imx) | Temporarily turns on the i, m, or x option within a regular expression. If inside parentheses, it only affects the part within the parentheses. |
| (?-imx) | Temporarily turns off the i, m, or x option within a regular expression. If inside parentheses, it only affects the part within the parentheses. |
| (?: re) | Groups a regular expression but does not remember the matched text. |
| (?imx: re) | Temporarily turns on the i, m, or x option within parentheses. |
| (?-imx: re) | Temporarily turns off the i, m, or x option within parentheses. |
| (?#...) | Comment. |
| (?= re) | Specifies a position using a pattern. Consumes no characters. |
| (?! re) | Specifies a position using the negation of a pattern. Consumes no characters. |
| (?> re) | Matches a standalone pattern with no backtracking. |
| \w | Matches a word character. |
| \W | Matches a non-word character. |
| \s | Matches a whitespace character. Equivalent to [\t\n\r\f]. |
| \S | Matches a non-whitespace character. |
| \d | Matches a digit. Equivalent to [0-9]. |
| \D | Matches a non-digit. |
| \A | Matches the beginning of a string. |
| \Z | Matches the end of a string. If there is a newline, it matches only before the newline. |
| \z | Matches the end of a string. |
| \G | Matches the point where the last match ended. |
| \b | Matches a word boundary when outside brackets, and matches a backspace (0x08) when inside brackets. |
| \B | Matches a non-word boundary. |
| \n, \t, etc. | Matches a newline, carriage return, tab, and so on. |
| \1...\9 | Matches the nth grouped subexpression. |
| \10 | If it has been matched before, matches the nth grouped subexpression. Otherwise, refers to the octal representation of a character code. |
Regular expression example
Character
| Example | Description |
|---|---|
| /ruby/ | Matches 'ruby' |
| ¥ | Matches the Yen symbol. Ruby 1.9 and Ruby 1.8 support multiple characters. |
Character class
| Example | Description |
|---|---|
| /[Rr]uby/ | Matches "Ruby" or "ruby" |
| /rub[ye]/ | Match "ruby" or "rube" |
| /[aeiou]/ | Matches any lowercase vowel letter |
| /[0-9]/ | Matches any digit, same as /[0123456789]/ |
| /[a-z]/ | Matches any lowercase ASCII letter |
| /[A-Z]/ | Matches any uppercase ASCII letter |
| /[a-zA-Z0-9]/ | Matches any character inside the brackets |
| /[^aeiou]/ | Matches any character that is not a lowercase vowel |
| /[^0-9]/ | Matches any non-digit character |
Special character classes
| Example | Description |
|---|---|
| /./ | Matches any character except a newline |
| /./m | In multiline mode, it can also match a newline |
| /\d/ | Matches a digit, equivalent to /[0-9]/ |
| /\D/ | Matches a non-digit, equivalent to /[^0-9]/ |
| /\s/ | Matches a whitespace character, equivalent to /[ \t\r\n\f]/ |
| /\S/ | Matches a non-whitespace character, equivalent to /[^ \t\r\n\f]/ |
| /\w/ | Matches a word character, equivalent to /[A-Za-z0-9_]/ |
| /\W/ | Matches a non-word character, equivalent to /[^A-Za-z0-9_]/ |
Repeat
| Example | Description |
|---|---|
| /ruby?/ | Matches 'rub' or 'ruby', where y is optional. |
| /ruby*/ | Matches "rub" plus zero or more y's. |
| /ruby+/ | Matches "rub" plus one or more y's. |
| /\d{3}/ | Matches exactly 3 digits. |
| /\d{3,}/ | Matches 3 or more digits. |
| /\d{3,5}/ | Matches 3, 4, or 5 digits. |
Non-greedy repetition
This matches the minimum number of repetitions.
| Example | Description |
|---|---|
| /<.*>/ | Greedy repetition: matches the '"perl>" |
| /<.*?>/ | Non-greedy repetition: matches the '""' in "perl>"" |
Grouping via parentheses
| Example | Description |
|---|---|
| /\D\d+/ | No grouping: + repeats \\d |
| /(\D\d)+/ | Grouping: + repeats \\D\\d pairs |
| /([Rr]uby(, )?)+/ | Matches "Ruby", "Ruby, ruby, ruby", and so on |
Backreference
This matches again the group that was previously matched.
| Example | Description |
|---|---|
| /([Rr])uby&\1ails/ | Matches ruby&rails or Ruby&Rails |
| /(['"])(?:(?!\1).)*\1/ | Single-quoted or double-quoted strings. \1 matches the characters matched by the first group, \2 matches those matched by the second group, and so on. |
Replacement
| Example | Description |
|---|---|
| /ruby|rube/ | Match "ruby" or "rube" |
| /rub(y|le)/ | Matches 'ruby' or 'ruble' |
| /ruby(!+|?)/ | 'ruby' followed by one or more ! or by a ? |
Anchors
These require specifying a match position.
| Example | Description |
|---|---|
| /^Ruby/ | Matches a string or line beginning with 'Ruby' |
| /Ruby$/ | Matches a string or line ending with 'Ruby' |
| /\ARuby/ | Matches a string beginning with 'Ruby' |
| /Ruby\Z/ | Matches a string ending with 'Ruby' |
| /\bRuby\b/ | Matches 'Ruby' at a word boundary |
| /\brub\B/ | \B is a non-word boundary: matches 'rub' in 'rube' and 'ruby', but not a standalone 'rub' |
| /Ruby(?=!)/ | Matches 'Ruby' if it is followed by an exclamation mark |
| /Ruby(?!!)/ | Matches 'Ruby' if it is not followed by an exclamation mark |
Special syntax with parentheses
| Example | Description |
|---|---|
| /R(?#comment)/ | Matches 'R'. All remaining characters are a comment. |
| /R(?i)uby/ | Case-insensitive when matching 'uby'. |
| /R(?i:uby)/ | Same as above. |
| /rub(?:y|le))/ | Groups only, without \1 backreferences |
Search and Replace
sub and gsub and their replacement variables sub! and gsub! are important string methods when using regular expressions.
All of these methods perform search and replace operations using regular expression patterns.sub and sub! replaces the first occurrence of the pattern,gsub and gsub! replaces all occurrences of the pattern.
sub and gsub returns a new string, leaving the original string unmodified, while sub! and gsub! modifies the string on which they are called.
Example
!/usr/bin/ruby
-- coding: UTF-8 --
phone
=
"
138-3453-1111 # this is a phone number
"
Removing Ruby comments
phone
=
phone
.
sub
!
(
/
#.*$
/
,
"
"
)
puts
"
Phone number : #{phone}
"
Removing characters other than digits
phone
=
phone
.
gsub
!
(
/
\D
/
,
"
"
)
puts
"
Phone number : #{phone}
"
Try it »
The above example produces the following output:
电话号码 : 138-3453-1111
电话号码 : 13834531111
Example
!/usr/bin/ruby
-- coding: UTF-8 --
text
=
"
rails is rails, Ruby on Rails is a very good Ruby framework
"
Change all 'rails' to 'Rails'
text
.
gsub
!
(
"
rails
"
,
"
Rails
"
)
Capitalize the first letter of all occurrences of the word 'Rails'
text
.
gsub
!
(
/
\b
rails
\b
/
,
"
Rails
"
)
puts
"
#{text}
"
Try it »
The above example produces the following output:
Rails 是 Rails, Ruby on Rails 非常好的 Ruby 框架