class Regexp
A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor.
You can create a Regexp object explicitly with:
Regular expressions (regexps) are patterns which describe the contents of a string. They’re used for testing whether a string contains a given pattern, or extracting the portions that match. They are created with the /pat/ and %r{pat} literals or the Regexp.new constructor.
A regexp is usually delimited with forward slashes (/). For example:
/hay/ =~ 'haystack' #=> 0 /y/.match('haystack') #=> #<MatchData "y">
If a string contains the pattern it is said to match. A literal string matches itself.
Here ‘haystack’ does not contain the pattern ‘needle’, so it doesn’t match:
/needle/.match('haystack') #=> nil
Here ‘haystack’ contains the pattern ‘hay’, so it matches:
/hay/.match('haystack') #=> #<MatchData "hay">
Specifically, /st/ requires that the string contains the letter s followed by the letter t, so it matches haystack, also.
=~ and Regexp#match¶ ↑
Pattern matching may be achieved by using =~ operator or Regexp#match method.
=~ operator¶ ↑
=~ is Ruby’s basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter. Other classes may have different implementations of =~.) If a match is found, the operator returns index of first match in string, otherwise it returns nil.
/hay/ =~ 'haystack' #=> 0 'haystack' =~ /hay/ #=> 0 /a/ =~ 'haystack' #=> 1 /u/ =~ 'haystack' #=> nil
Using =~ operator with a String and Regexp the $~ global variable is set after a successful match. $~ holds a MatchData object. Regexp.last_match is equivalent to $~.
Regexp#match method¶ ↑
The match method returns a MatchData object:
/st/.match('haystack') #=> #<MatchData "st">
Metacharacters and Escapes¶ ↑
The following are metacharacters (, ), [, ], {, }, ., ?, +, *. They have a specific meaning when appearing in a pattern. To match them literally they must be backslash-escaped. To match a backslash literally, backslash-escape it: \\.
/1 \+ 2 = 3\?/.match('Does 1 + 2 = 3?') #=> #<MatchData "1 + 2 = 3?"> /a\\\\b/.match('a\\\\b') #=> #<MatchData "a\\b">
Patterns behave like double-quoted strings and can contain the same backslash escapes (the meaning of \s is different, however, see below).
/\s\u{6771 4eac 90fd}/.match("Go to 東京都") #=> #<MatchData " 東京都">
Arbitrary Ruby expressions can be embedded into patterns with the #{...} construct.
place = "東京都" /#{place}/.match("Go to 東京都") #=> #<MatchData "東京都">
Character Classes¶ ↑
A character class is delimited with square brackets ([, ]) and lists characters that may appear at that point in the match. /[ab]/ means a or b, as opposed to /ab/ which means a followed by b.
/W[aeiou]rd/.match("Word") #=> #<MatchData "Word">
Within a character class the hyphen (-) is a metacharacter denoting an inclusive range of characters. [abcd] is equivalent to [a-d]. A range can be followed by another range, so [abcdwxyz] is equivalent to [a-dw-z]. The order in which ranges or individual characters appear inside a character class is irrelevant.
/[0-9a-f]/.match('9f') #=> #<MatchData "9"> /[9f]/.match('9f') #=> #<MatchData "9">
If the first character of a character class is a caret (^) the class is inverted: it matches any character except those named.
/[^a-eg-z]/.match('f') #=> #<MatchData "f">
A character class may contain another character class. By itself this isn’t useful because [a-z[0-9]] describes the same set as [a-z0-9]. However, character classes also support the && operator which performs set intersection on its arguments. The two can be combined as follows:
/[a-w&&[^c-g]z]/ # ([a-w] AND ([^c-g] OR z))
This is equivalent to:
/[abh-w]/
The following metacharacters also behave like character classes:
-
/./- Any character except a newline. -
/./m- Any character (themmodifier enables multiline mode) -
/\w/- A word character ([a-zA-Z0-9_]) -
/\W/- A non-word character ([^a-zA-Z0-9_]). Please take a look at Bug #4044 if using/\W/with the/imodifier. -
/\d/- A digit character ([0-9]) -
/\D/- A non-digit character ([^0-9]) -
/\h/- A hexdigit character ([0-9a-fA-F]) -
/\H/- A non-hexdigit character ([^0-9a-fA-F]) -
/\s/- A whitespace character:/[ \t\r\n\f\v]/ -
/\S/- A non-whitespace character:/[^ \t\r\n\f\v]/ -
/\R/- A linebreak:\n,\v,\f,\r\u0085(NEXT LINE),\u2028(LINE SEPARATOR),\u2029(PARAGRAPH SEPARATOR) or\r\n.
POSIX bracket expressions are also similar to character classes. They provide a portable alternative to the above, with the added benefit that they encompass non-ASCII characters. For instance, /\d/ matches only the ASCII decimal digits (0-9); whereas /[[:digit:]]/ matches any character in the Unicode Nd category.
-
/[[:alnum:]]/- Alphabetic and numeric character -
/[[:alpha:]]/- Alphabetic character -
/[[:blank:]]/- Space or tab -
/[[:cntrl:]]/- Control character -
/[[:digit:]]/- Digit -
/[[:graph:]]/- Non-blank character (excludes spaces, control characters, and similar) -
/[[:lower:]]/- Lowercase alphabetical character -
/[[:print:]]/- Like [:graph:], but includes the space character -
/[[:punct:]]/- Punctuation character -
/[[:space:]]/- Whitespace character ([:blank:], newline, carriage return, etc.) -
/[[:upper:]]/- Uppercase alphabetical -
/[[:xdigit:]]/- Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F)
Ruby also supports the following non-POSIX character classes:
-
/[[:word:]]/- A character in one of the following Unicode general categories Letter, Mark, Number, Connector_Punctuation -
/[[:ascii:]]/- A character in the ASCII character set# U+06F2 is "EXTENDED ARABIC-INDIC DIGIT TWO" /[[:digit:]]/.match("\u06F2") #=> #<MatchData "\u{06F2}"> /[[:upper:]][[:lower:]]/.match("Hello") #=> #<MatchData "He"> /[[:xdigit:]][[:xdigit:]]/.match("A6") #=> #<MatchData "A6">