class Regexp

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 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.

Note that any Regexp matching will raise a RuntimeError if timeout is set and exceeded. See “Timeout” section in detail.

Regexp Interpolation

A regexp may contain interpolated strings; trivially:

foo = 'bar'
/#{foo}/ # => /bar/

=~ 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:


The following metacharacters also behave like character classes:

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.

Ruby also supports the following non-POSIX character classes:


The constructs described so far match a single character. They can be followed by a repetition metacharacter to specify how many times they need to occur. Such metacharacters are called quantifiers.

At least one uppercase character (‘H’), at least one lowercase character (‘e’), two ‘l’ characters, then one ‘o’:

"Hello".match(/[[:upper:]]+[[:lower:]]+l{2}o/) #=> #<MatchData "Hello">

Greedy Match

Repetition is greedy by default: as many occurrences as possible are matched while still allowing the overall match to succeed. By contrast, lazy matching makes the minimal amount of matches necessary for overall success. Most greedy metacharacters can be made lazy by following them with ?. For the {n} pattern, because it specifies an exact number of characters to match and not a variable number of characters, the ? metacharacter instead makes the repeated pattern optional.

Both patterns below match the string. The first uses a greedy quantifier so ‘.+’ matches ‘<a><b>’; the second uses a lazy quantifier so ‘.+?’ matches ‘<a>’:

/<.+>/.match("<a><b>")  #=> #<MatchData "<a><b>">
/<.+?>/.match("<a><b>") #=> #<MatchData "<a>">

Possessive Match

A quantifier followed by + matches possessively: once it has matched it does not backtrack. They behave like greedy quantifiers, but having matched they refuse to “give up” their match even if this jeopardises the overall match.

/<.*><.+>/.match("<a><b>") #=> #<MatchData "<a><b>">
/<.*+><.+>/.match("<a><b>") #=> nil
/<.*><.++>/.match("<a><b>") #=> nil


Parentheses can be used for capturing. The text enclosed by the nth group of parentheses can be subsequently referred to with n. Within a pattern use the backreference \n (e.g. \1); outside of the pattern use MatchData[n] (e.g. MatchData[1]).

In this example, 'at' is captured by the first group of parentheses, then referred to later with \1:

/[csh](..) [csh]\1 in/.match("The cat sat in the hat")
    #=> #<MatchData "cat sat in" 1:"at">

Regexp#match returns a MatchData object which makes the captured text available with its [] method:

/[csh](..) [csh]\1 in/.match("The cat sat in the hat")[1] #=> 'at'

While Ruby supports an arbitrary number of numbered captured groups, only groups 1-9 are supported using the \n backreference syntax.

Ruby also supports \0 as a special backreference, which references the entire matched string. This is also available at MatchData[0]. Note that the \0 backreference cannot be used inside the regexp, as backreferences can only be used after the end of the capture group, and the \0 backreference uses the implicit capture group of the entire match. However, you can use this backreference when doing substitution:

"The cat sat in the hat".gsub(/[csh]at/, '\0s')
  # => "The cats sats in the hats"

Named Captures

Capture groups can be referred to by name when defined with the (?<name>) or (?'name') constructs.

    #=> #<MatchData "$3.67" dollars:"3" cents:"67">
/\$(?<dollars>\d+)\.(?<cents>\d+)/.match("$3.67")[:dollars] #=> "3"

Named groups can be backreferenced with \k<name>, where name is the group name.

    #=> #<MatchData "ototo" vowel:"o">

Note: A regexp can’t use named backreferences and numbered backreferences simultaneously. Also, if a named capture is used in a regexp, then parentheses used for grouping which would otherwise result in a unnamed capture are treated as non-capturing.

/(\w)(\w)/.match("ab").captures # => ["a", "b"]
/(\w)(\w)/.match("ab").named_captures # => {}

/(?<c>\w)(\w)/.match("ab").captures # => ["a"]
/(?<c>\w)(\w)/.match("ab").named_captures # => {"c"=>"a"}

When named capture groups are used with a literal regexp on the left-hand side of an expression and the =~ operator, the captured text is also assigned to local variables with corresponding names.

/\$(?<dollars>\d+)\.(?<cents>\d+)/ =~ "$3.67" #=> 0
dollars #=> "3"


Parentheses also group the terms they enclose, allowing them to be quantified as one atomic whole.

The pattern below matches a vowel followed by 2 word characters:

/[aeiou]\w{2}/.match("Caenorhabditis elegans") #=> #<MatchData "aen">

Whereas the following pattern matches a vowel followed by a word character, twice, i.e. [aeiou]\w[aeiou]\w: ‘enor’.

/([aeiou]\w){2}/.match("Caenorhabditis elegans")
    #=> #<MatchData "enor" 1:"or">

The (?:) construct provides grouping without capturing. That is, it combines the terms it contains into an atomic whole without creating a backreference. This benefits performance at the slight expense of readability.

The first group of parentheses captures ‘n’ and the second ‘ti’. The second group is referred to later with the backreference \2:

    #=> #<MatchData "Investigations" 1:"n" 2:"ti">

The first group of parentheses is now made non-capturing with ‘?:’, so it still matches ‘n’, but doesn’t create the backreference. Thus, the backreference \1 now refers to ‘ti’.

    #=> #<MatchData "Investigations" 1:"ti">

Atomic Grouping

Grouping can be made atomic with (?>pat). This causes the subexpression pat to be matched independently of the rest of the expression such that what it matches becomes fixed for the remainder of the match, unless the entire subexpression must be abandoned and subsequently revisited. In this way pat is treated as a non-divisible whole. Atomic grouping is typically used to optimise patterns so as to prevent the regular expression engine from backtracking needlessly.

The " in the pattern below matches the first character of the string, then .* matches Quote“. This causes the overall match to fail, so the text matched by .* is backtracked by one position, which leaves the final character of the string available to match "

/".*"/.match('"Quote"')     #=> #<MatchData "\"Quote\"">

If .* is grouped atomically, it refuses to backtrack Quote“, even though this means that the overall match fails

/"(?>.*)"/.match('"Quote"') #=> nil

Subexpression Calls

The \g<name> syntax matches the previous subexpression named name, which can be a group name or number, again. This differs from backreferences in that it re-executes the group rather than simply trying to re-match the same text.

This pattern matches a ( character and assigns it to the paren group, tries to call that the paren sub-expression again but fails, then matches a literal ):

/\A(?<paren>\(\g<paren>*\))*\z/ =~ '()'

/\A(?<paren>\(\g<paren>*\))*\z/ =~ '(())' #=> 0
# ^1
#      ^2
#           ^3
#                 ^4
#      ^5
#           ^6
#                      ^7
#                       ^8
#                       ^9
#                           ^10
  1. Matches at the beginning of the string, i.e. before the first character.

  2. Enters a named capture group called paren

  3. Matches a literal (, the first character in the string

  4. Calls the paren group again, i.e. recurses back to the second step

  5. Re-enters the paren group

  6. Matches a literal (, the second character in the string

  7. Try to call paren a third time, but fail because doing so would prevent an overall successful match

  8. Match a literal ), the third character in the string. Marks the end of the second recursive call

  9. Match a literal ), the fourth character in the string

  10. Match the end of the string


The vertical bar metacharacter (|) combines several expressions into a single one that matches any of the expressions. Each expression is an alternative.

/\w(and|or)\w/.match("Feliformia") #=> #<MatchData "form" 1:"or">
/\w(and|or)\w/.match("furandi")    #=> #<MatchData "randi" 1:"and">
/\w(and|or)\w/.match("dissemblance") #=> nil


The (?(cond)yes|no) syntax matches yes part if cond is captured, otherwise matches no part. In the case no part is empty, also | can be omitted.

The cond may be a backreference number or a captured name. A backreference number is an absolute position, but can not be a relative position.

Character Properties

The \p{} construct matches characters with the named property, much like POSIX bracket classes.

A Unicode character’s General Category value can also be matched with \p{Ab} where Ab is the category’s abbreviation as described below:

Lastly, \p{} matches a character’s Unicode script. The following scripts are supported: Arabic, Armenian, Balinese, Bengali, Bopomofo, Braille, Buginese, Buhid, Canadian_Aboriginal, Carian, Cham, Cherokee, Common, Coptic, Cuneiform, Cypriot, Cyrillic, Deseret, Devanagari, Ethiopic, Georgian, Glagolitic, Gothic, Greek, Gujarati, Gurmukhi, Han, Hangul, Hanunoo, Hebrew, Hiragana, Inherited, Kannada, Katakana, Kayah_Li, Kharoshthi, Khmer, Lao, Latin, Lepcha, Limbu, Linear_B, Lycian, Lydian, Malayalam, Mongolian, Myanmar, New_Tai_Lue, Nko, Ogham, Ol_Chiki, Old_Italic, Old_Persian, Oriya, Osmanya, Phags_Pa, Phoenician, Rejang, Runic, Saurashtra, Shavian, Sinhala, Sundanese, Syloti_Nagri, Syriac, Tagalog, Tagbanwa, Tai_Le, Tamil, Telugu, Thaana, Thai, Tibetan, Tifinagh, Ugaritic, Vai, and Yi.

Unicode codepoint U+06E9 is named “ARABIC PLACE OF SAJDAH” and belongs to the Arabic script:

/\p{Arabic}/.match("\u06E9") #=> #<MatchData "\u06E9">

All character properties can be inverted by prefixing their name with a caret (^).

Letter ‘A’ is not in the Unicode Ll (Letter; Lowercase) category, so this match succeeds:

/\p{^Ll}/.match("A") #=> #<MatchData "A">


Anchors are metacharacter that match the zero-width positions between characters, anchoring the match to a specific position.

If a pattern isn’t anchored it can begin at any point in the string:

/real/.match("surrealist") #=> #<MatchData "real">

Anchoring the pattern to the beginning of the string forces the match to start there. ‘real’ doesn’t occur at the beginning of the string, so now the match fails:

/\Areal/.match("surrealist") #=> nil

The match below fails because although ‘Demand’ contains ‘and’, the pattern does not occur at a word boundary.


Whereas in the following example ‘and’ has been anchored to a non-word boundary so instead of matching the first ‘and’ it matches from the fourth letter of ‘demand’ instead:

/\Band.+/.match("Supply and demand curve") #=> #<MatchData "and curve">

The pattern below uses positive lookahead and positive lookbehind to match text appearing in tags without including the tags in the match:

/(?<=<b>)\w+(?=<\/b>)/.match("Fortune favours the <b>bold</b>")
    #=> #<MatchData "bold">


The end delimiter for a regexp can be followed by one or more single-letter options which control how the pattern can match.

i, m, and x can also be applied on the subexpression level with the (?on-off) construct, which enables options on, and disables options off for the expression enclosed by the parentheses:

/a(?i:b)c/.match('aBc')   #=> #<MatchData "aBc">
/a(?-i:b)c/i.match('ABC') #=> nil

Additionally, these options can also be toggled for the remainder of the pattern:

/a(?i)bc/.match('abC') #=> #<MatchData "abC">

Options may also be used with"abc", Regexp::IGNORECASE)                     #=> /abc/i"abc", Regexp::MULTILINE)                      #=> /abc/m"abc # Comment", Regexp::EXTENDED)             #=> /abc # Comment/x"abc", Regexp::IGNORECASE | Regexp::MULTILINE) #=> /abc/mi"abc", "i")           #=> /abc/i"abc", "m")           #=> /abc/m"abc # Comment", "x") #=> /abc # Comment/x"abc", "im")          #=> /abc/mi

Free-Spacing Mode and Comments

As mentioned above, the x option enables free-spacing mode. Literal white space inside the pattern is ignored, and the octothorpe (#) character introduces a comment until the end of the line. This allows the components of the pattern to be organized in a potentially more readable fashion.

A contrived pattern to match a number with optional decimal places:

float_pat = /\A
    [[:digit:]]+ # 1 or more digits before the decimal point
    (\.          # Decimal point
        [[:digit:]]+ # 1 or more digits after the decimal point
    )? # The decimal point and following digits are optional
float_pat.match('3.14') #=> #<MatchData "3.14" 1:".14">

There are a number of strategies for matching whitespace:

Comments can be included in a non-x pattern with the (?#comment) construct, where comment is arbitrary text ignored by the regexp engine.

Comments in regexp literals cannot include unescaped terminator characters.


Regular expressions are assumed to use the source encoding. This can be overridden with one of the following modifiers.

A regexp can be matched against a string when they either share an encoding, or the regexp’s encoding is US-ASCII and the string’s encoding is ASCII-compatible.

If a match between incompatible encodings is attempted an Encoding::CompatibilityError exception is raised.

The Regexp#fixed_encoding? predicate indicates whether the regexp has a fixed encoding, that is one incompatible with ASCII. A regexp’s encoding can be explicitly fixed by supplying Regexp::FIXEDENCODING as the second argument of

r ="a".force_encoding("iso-8859-1"),Regexp::FIXEDENCODING)
r =~ "a\u3042"
   # raises Encoding::CompatibilityError: incompatible encoding regexp match
   #         (ISO-8859-1 regexp with UTF-8 string)

Regexp Global Variables

Pattern matching sets some global variables :


m = /s(\w{2}).*(c)/.match('haystack') #=> #<MatchData "stac" 1:"ta" 2:"c">
$~                                    #=> #<MatchData "stac" 1:"ta" 2:"c">
Regexp.last_match                     #=> #<MatchData "stac" 1:"ta" 2:"c">

$&      #=> "stac"
        # same as m[0]
$`      #=> "hay"
        # same as m.pre_match
$'      #=> "k"
        # same as m.post_match
$1      #=> "ta"
        # same as m[1]
$2      #=> "c"
        # same as m[2]
$3      #=> nil
        # no third group in pattern
$+      #=> "c"
        # same as m[-1]

These global variables are thread-local and method-local variables.


Certain pathological combinations of constructs can lead to abysmally bad performance.

Consider a string of 25 as, a d, 4 as, and a c.

s = 'a' * 25 + 'd' + 'a' * 4 + 'c'
#=> "aaaaaaaaaaaaaaaaaaaaaaaaadaaaac"

The following patterns match instantly as you would expect:

/(b|a)/ =~ s #=> 0
/(b|a+)/ =~ s #=> 0
/(b|a+)*/ =~ s #=> 0

However, the following pattern takes appreciably longer:

/(b|a+)*c/ =~ s #=> 26

This happens because an atom in the regexp is quantified by both an immediate + and an enclosing * with nothing to differentiate which is in control of any particular character. The nondeterminism that results produces super-linear performance. (Consult Mastering Regular Expressions (3rd ed.), pp 222, by Jeffery Friedl, for an in-depth analysis). This particular case can be fixed by use of atomic grouping, which prevents the unnecessary backtracking:

(start = && /(b|a+)*c/ =~ s && ( - start)
   #=> 24.702736882
(start = && /(?>b|a+)*c/ =~ s && ( - start)
   #=> 0.000166571

A similar case is typified by the following example, which takes approximately 60 seconds to execute for me:

Match a string of 29 as against a pattern of 29 optional as followed by 29 mandatory as:'a?' * 29 + 'a' * 29) =~ 'a' * 29

The 29 optional as match the string, but this prevents the 29 mandatory as that follow from matching. Ruby must then backtrack repeatedly so as to satisfy as many of the optional matches as it can while still matching the mandatory 29. It is plain to us that none of the optional matches can succeed, but this fact unfortunately eludes Ruby.

The best way to improve performance is to significantly reduce the amount of backtracking needed. For this case, instead of individually matching 29 optional as, a range of optional as can be matched all at once with a{0,29}:'a{0,29}' + 'a' * 29) =~ 'a' * 29


There are two APIs to set timeout. One is Regexp.timeout=, which is process-global configuration of timeout for Regexp matching.

Regexp.timeout = 3
s = 'a' * 25 + 'd' + 'a' * 4 + 'c'
/(b|a+)*c/ =~ s  #=> This raises an exception in three seconds

The other is timeout keyword of

re ="(b|a+)*c", timeout: 3)
s = 'a' * 25 + 'd' + 'a' * 4 + 'c'
/(b|a+)*c/ =~ s  #=> This raises an exception in three seconds

When using Regexps to process untrusted input, you should use the timeout feature to avoid excessive backtracking. Otherwise, a malicious user can provide input to Regexp causing Denial-of-Service attack. Note that the timeout is not set by default because an appropriate limit highly depends on an application requirement and context.



see Regexp.options and


see Regexp.options and


see Regexp.options and


see Regexp.options and


see Regexp.options and

Public Class Methods


Alias for

escape(string) → new_string click to toggle source

Returns a new string that escapes any characters that have special meaning in a regular expression:

s = Regexp.escape('\*?{}.')      # => "\\\\\\*\\?\\{\\}\\."

For any string s, this call returns a MatchData object:

r = # => /\\\\\\\*\\\?\\\{\\\}\\\./
r.match(s)                       # => #<MatchData "\\\\\\*\\?\\{\\}\\.">
static VALUE
rb_reg_s_quote(VALUE c, VALUE str)
    return rb_reg_quote(reg_operand(str, TRUE));
json_create(object) click to toggle source

Deserializes JSON string by constructing new Regexp object with source s (Regexp or String) and options o serialized by to_json

# File ext/json/lib/json/add/regexp.rb, line 11
def self.json_create(object)
  new(object['s'], object['o'])
last_match → matchdata or nil click to toggle source
last_match(n) → string or nil
last_match(name) → string or nil

With no argument, returns the value of $!, which is the result of the most recent pattern match (see Regexp Global Variables):

/c(.)t/ =~ 'cat'  # => 0
Regexp.last_match # => #<MatchData "cat" 1:"a">
/a/ =~ 'foo'      # => nil
Regexp.last_match # => nil

With non-negative integer argument n, returns the _n_th field in the matchdata, if any, or nil if none:

/c(.)t/ =~ 'cat'     # => 0
Regexp.last_match(0) # => "cat"
Regexp.last_match(1) # => "a"
Regexp.last_match(2) # => nil

With negative integer argument n, counts backwards from the last field:

Regexp.last_match(-1)       # => "a"

With string or symbol argument name, returns the string value for the named capture, if any:

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ 'var = val'
Regexp.last_match        # => #<MatchData "var = val" lhs:"var"rhs:"val">
Regexp.last_match(:lhs)  # => "var"
Regexp.last_match('rhs') # => "val"
Regexp.last_match('foo') # Raises IndexError.
static VALUE
rb_reg_s_last_match(int argc, VALUE *argv, VALUE _)
    if (rb_check_arity(argc, 0, 1) == 1) {
        VALUE match = rb_backref_get();
        int n;
        if (NIL_P(match)) return Qnil;
        n = match_backref_number(match, argv[0]);
        return rb_reg_nth_match(n, match);
    return match_getter();
linear_time?(re) click to toggle source
linear_time?(string, options = 0)

Returns true if matching against re can be done in linear time to the input string.

Regexp.linear_time?(/re/) # => true

Note that this is a property of the ruby interpreter, not of the argument regular expression. Identical regexp can or cannot run in linear time depending on your ruby binary. Neither forward nor backward compatibility is guaranteed about the return value of this method. Our current algorithm is (*1) but this is subject to change in the future. Alternative implementations can also behave differently. They might always return false for everything.


static VALUE
rb_reg_s_linear_time_p(int argc, VALUE *argv, VALUE self)
    struct reg_init_args args;
    VALUE re = reg_extract_args(argc, argv, &args);

    if (NIL_P(re)) {
        re = reg_init_args(rb_reg_alloc(), args.str, args.enc, args.flags);

    return RBOOL(onig_check_linear_time(RREGEXP_PTR(re)));
new(string, options = 0, timeout: nil) → regexp click to toggle source
new(regexp, timeout: nil) → regexp

With argument string given, returns a new regexp with the given string and options:

r ='foo') # => /foo/
r.source              # => "foo"
r.options             # => 0

Optional argument options is one of the following:

  • A String of options:'foo', 'i')  # => /foo/i'foo', 'im') # => /foo/im
  • The bit-wise OR of one or more of the constants Regexp::EXTENDED, Regexp::IGNORECASE, Regexp::MULTILINE, and Regexp::NOENCODING:'foo', Regexp::IGNORECASE) # => /foo/i'foo', Regexp::EXTENDED)   # => /foo/x'foo', Regexp::MULTILINE)  # => /foo/m'foo', Regexp::NOENCODING)  # => /foo/n
    flags = Regexp::IGNORECASE | Regexp::EXTENDED |  Regexp::MULTILINE'foo', flags)              # => /foo/mix
  • nil or false, which is ignored.

  • Any other truthy value, in which case the regexp will be case-insensitive.

If optional keyword argument timeout is given, its float value overrides the timeout interval for the class, Regexp.timeout. If nil is passed as +timeout, it uses the timeout interval for the class, Regexp.timeout.

With argument regexp given, returns a new regexp. The source, options, timeout are the same as regexp. options and n_flag arguments are ineffective. The timeout can be overridden by timeout keyword.

options = Regexp::MULTILINE
r ='foo', options, timeout: 1.1) # => /foo/m
r2 =                           # => /foo/m
r2.timeout                                   # => 1.1
r3 =, timeout: 3.14)            # => /foo/m
r3.timeout                                   # => 3.14
static VALUE
rb_reg_initialize_m(int argc, VALUE *argv, VALUE self)
    struct reg_init_args args;

    reg_extract_args(argc, argv, &args);
    reg_init_args(self, args.str, args.enc, args.flags);

    set_timeout(&RREGEXP_PTR(self)->timelimit, args.timeout);

    return self;
escape(string) → new_string click to toggle source

Returns a new string that escapes any characters that have special meaning in a regular expression:

s = Regexp.escape('\*?{}.')      # => "\\\\\\*\\?\\{\\}\\."

For any string s, this call returns a MatchData object:

r = # => /\\\\\\\*\\\?\\\{\\\}\\\./
r.match(s)                       # => #<MatchData "\\\\\\*\\?\\{\\}\\.">
static VALUE
rb_reg_s_quote(VALUE c, VALUE str)
    return rb_reg_quote(reg_operand(str, TRUE));
timeout → float or nil click to toggle source

It returns the current default timeout interval for Regexp matching in second. nil means no default timeout configuration.

static VALUE
rb_reg_s_timeout_get(VALUE dummy)
    double d = hrtime2double(rb_reg_match_time_limit);
    if (d == 0.0) return Qnil;
    return DBL2NUM(d);
timeout = float or nil click to toggle source

It sets the default timeout interval for Regexp matching in second. nil means no default timeout configuration. This configuration is process-global. If you want to set timeout for each Regexp, use timeout keyword for

Regexp.timeout = 1
/^a*b?a*$/ =~ "a" * 100000 + "x" #=> regexp match timeout (RuntimeError)
static VALUE
rb_reg_s_timeout_set(VALUE dummy, VALUE timeout)
    rb_ractor_ensure_main_ractor("can not access Regexp.timeout from non-main Ractors");

    set_timeout(&rb_reg_match_time_limit, timeout);

    return timeout;
try_convert(object) → regexp or nil click to toggle source

Returns object if it is a regexp:

Regexp.try_convert(/re/) # => /re/

Otherwise if object responds to :to_regexp, calls object.to_regexp and returns the result.

Returns nil if object does not respond to :to_regexp.

Regexp.try_convert('re') # => nil

Raises an exception unless object.to_regexp returns a regexp.

static VALUE
rb_reg_s_try_convert(VALUE dummy, VALUE re)
    return rb_check_regexp_type(re);
union(*patterns) → regexp click to toggle source
union(array_of_patterns) → regexp

Returns a new regexp that is the union of the given patterns:

r = Regexp.union(%w[cat dog])      # => /cat|dog/
r.match('cat')      # => #<MatchData "cat">
r.match('dog')      # => #<MatchData "dog">
r.match('cog')      # => nil

For each pattern that is a string, is used:

Regexp.union('penzance')             # => /penzance/
Regexp.union('a+b*c')                # => /a\+b\*c/
Regexp.union('skiing', 'sledding')   # => /skiing|sledding/
Regexp.union(['skiing', 'sledding']) # => /skiing|sledding/

For each pattern that is a regexp, it is used as is, including its flags:

Regexp.union(/foo/i, /bar/m, /baz/x)
# => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/
Regexp.union([/foo/i, /bar/m, /baz/x])
# => /(?i-mx:foo)|(?m-ix:bar)|(?x-mi:baz)/

With no arguments, returns /(?!)/:

Regexp.union # => /(?!)/

If any regexp pattern contains captures, the behavior is unspecified.

static VALUE
rb_reg_s_union_m(VALUE self, VALUE args)
    VALUE v;
    if (RARRAY_LEN(args) == 1 &&
        !NIL_P(v = rb_check_array_type(rb_ary_entry(args, 0)))) {
        return rb_reg_s_union(self, v);
    return rb_reg_s_union(self, args);

Public Instance Methods

regexp == object → true or false

Returns true if object is another Regexp whose pattern, flags, and encoding are the same as self, false otherwise:

/foo/ =='foo')                          # => true
/foo/ == /foo/i                                     # => false
/foo/ =='food')                         # => false
/foo/ =="abc".force_encoding("euc-jp")) # => false
Alias for: eql?
regexp === string → true or false click to toggle source

Returns true if self finds a match in string:

/^[a-z]*$/ === 'HELLO' # => false
/^[A-Z]*$/ === 'HELLO' # => true

This method is called in case statements:

s = 'HELLO'
case s
when /\A[a-z]*\z/; print "Lower case\n"
when /\A[A-Z]*\z/; print "Upper case\n"
else               print "Mixed case\n"
end # => "Upper case"
static VALUE
rb_reg_eqq(VALUE re, VALUE str)
    long start;

    str = reg_operand(str, FALSE);
    if (NIL_P(str)) {
        return Qfalse;
    start = rb_reg_search(re, str, 0, 0);
    return RBOOL(start >= 0);
regexp =~ string → integer or nil click to toggle source

Returns the integer index (in characters) of the first match for self and string, or nil if none; also sets the rdoc-ref:Regexp Global Variables:

/at/ =~ 'input data' # => 7
$~                   # => #<MatchData "at">
/ax/ =~ 'input data' # => nil
$~                   # => nil

Assigns named captures to local variables of the same names if and only if self:

  • Is a regexp literal; see Regexp Literals.

  • Does not contain interpolations; see Regexp Interpolation.

  • Is at the left of the expression.


/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ '  x = y  '
p lhs # => "x"
p rhs # => "y"

Assigns nil if not matched:

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ '  x = '
p lhs # => nil
p rhs # => nil

Does not make local variable assignments if self is not a regexp literal:

r = /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
r =~ '  x = y  '
p foo # Undefined local variable
p bar # Undefined local variable

The assignment does not occur if the regexp is not at the left:

'  x = y  ' =~ /(?<foo>\w+)\s*=\s*(?<foo>\w+)/
p foo, foo # Undefined local variables

A regexp interpolation, #{}, also disables the assignment:

r = /(?<foo>\w+)/
/(?<foo>\w+)\s*=\s*#{r}/ =~ 'x = y'
p foo # Undefined local variable
rb_reg_match(VALUE re, VALUE str)
    long pos = reg_match_pos(re, &str, 0, NULL);
    if (pos < 0) return Qnil;
    pos = rb_str_sublen(str, pos);
    return LONG2FIX(pos);
as_json(*) click to toggle source

Returns a hash, that will be turned into a JSON object and represent this object.

# File ext/json/lib/json/add/regexp.rb, line 17
def as_json(*)
    JSON.create_id =>,
    'o'            => options,
    's'            => source,
casefold?→ true or false click to toggle source

Returns true if the case-insensitivity flag in self is set, false otherwise:

/a/.casefold?           # => false
/a/i.casefold?          # => true
/(?i:a)/.casefold?      # => false
static VALUE
rb_reg_casefold_p(VALUE re)
encoding → encoding click to toggle source

Returns the Encoding object that represents the encoding of obj.

rb_obj_encoding(VALUE obj)
    int idx = rb_enc_get_index(obj);
    if (idx < 0) {
        rb_raise(rb_eTypeError, "unknown encoding");
    return rb_enc_from_encoding_index(idx & ENC_INDEX_MASK);
eql? == object -> true or false click to toggle source

Returns true if object is another Regexp whose pattern, flags, and encoding are the same as self, false otherwise:

/foo/ =='foo')                          # => true
/foo/ == /foo/i                                     # => false
/foo/ =='food')                         # => false
/foo/ =="abc".force_encoding("euc-jp")) # => false
rb_reg_equal(VALUE re1, VALUE re2)
    if (re1 == re2) return Qtrue;
    if (!RB_TYPE_P(re2, T_REGEXP)) return Qfalse;
    rb_reg_check(re1); rb_reg_check(re2);
    if (FL_TEST(re1, KCODE_FIXED) != FL_TEST(re2, KCODE_FIXED)) return Qfalse;
    if (RREGEXP_PTR(re1)->options != RREGEXP_PTR(re2)->options) return Qfalse;
    if (RREGEXP_SRC_LEN(re1) != RREGEXP_SRC_LEN(re2)) return Qfalse;
    if (ENCODING_GET(re1) != ENCODING_GET(re2)) return Qfalse;
    return RBOOL(memcmp(RREGEXP_SRC_PTR(re1), RREGEXP_SRC_PTR(re2), RREGEXP_SRC_LEN(re1)) == 0);
Also aliased as: ==
fixed_encoding? → true or false click to toggle source

Returns false if self is applicable to a string with any ASCII-compatible encoding; otherwise returns true:

r = /a/                                          # => /a/
r.fixed_encoding?                               # => false
r.match?("\u{6666} a")                          # => true
r.match?("\xa1\xa2 a".force_encoding("euc-jp")) # => true
r.match?("abc".force_encoding("euc-jp"))        # => true

r = /a/u                                        # => /a/
r.fixed_encoding?                               # => true
r.match?("\u{6666} a")                          # => true
r.match?("\xa1\xa2".force_encoding("euc-jp"))   # Raises exception.
r.match?("abc".force_encoding("euc-jp"))        # => true

r = /\u{6666}/                                  # => /\u{6666}/
r.fixed_encoding?                               # => true
r.encoding                                      # => #<Encoding:UTF-8>
r.match?("\u{6666} a")                          # => true
r.match?("\xa1\xa2".force_encoding("euc-jp"))   # Raises exception.
r.match?("abc".force_encoding("euc-jp"))        # => false
static VALUE
rb_reg_fixed_encoding_p(VALUE re)
    return RBOOL(FL_TEST(re, KCODE_FIXED));
hash → integer click to toggle source

Returns the integer hash value for self.

Related: Object#hash.

rb_reg_hash(VALUE re)
    st_index_t hashval = reg_hash(re);
    return ST2FIX(hashval);
inspect → string click to toggle source

Returns a nicely-formatted string representation of self:

/ab+c/ix.inspect # => "/ab+c/ix"

Related: Regexp#to_s.

static VALUE
rb_reg_inspect(VALUE re)
    if (!RREGEXP_PTR(re) || !RREGEXP_SRC(re) || !RREGEXP_SRC_PTR(re)) {
        return rb_any_to_s(re);
    return rb_reg_desc(RREGEXP_SRC_PTR(re), RREGEXP_SRC_LEN(re), re);
match(string, offset = 0) → matchdata or nil click to toggle source
match(string, offset = 0) {|matchdata| ... } → object

With no block given, returns the MatchData object that describes the match, if any, or nil if none; the search begins at the given character offset in string:

/abra/.match('abracadabra')      # => #<MatchData "abra">
/abra/.match('abracadabra', 4)   # => #<MatchData "abra">
/abra/.match('abracadabra', 8)   # => nil
/abra/.match('abracadabra', 800) # => nil

string = "\u{5d0 5d1 5e8 5d0}cadabra"
/abra/.match(string, 7)          #=> #<MatchData "abra">
/abra/.match(string, 8)          #=> nil
/abra/.match(string.b, 8)        #=> #<MatchData "abra">

With a block given, calls the block if and only if a match is found; returns the block’s value:

/abra/.match('abracadabra') {|matchdata| p matchdata }
# => #<MatchData "abra">
/abra/.match('abracadabra', 4) {|matchdata| p matchdata }
# => #<MatchData "abra">
/abra/.match('abracadabra', 8) {|matchdata| p matchdata }
# => nil
/abra/.match('abracadabra', 8) {|marchdata| fail 'Cannot happen' }
# => nil

Output (from the first two blocks above):

#<MatchData "abra">
#<MatchData "abra">

 /(.)(.)(.)/.match("abc")[2] # => "b"
 /(.)(.)/.match("abc", 1)[2] # => "c"
static VALUE
rb_reg_match_m(int argc, VALUE *argv, VALUE re)
    VALUE result = Qnil, str, initpos;
    long pos;

    if (rb_scan_args(argc, argv, "11", &str, &initpos) == 2) {
        pos = NUM2LONG(initpos);
    else {
        pos = 0;

    pos = reg_match_pos(re, &str, pos, &result);
    if (pos < 0) {
        return Qnil;
    if (!NIL_P(result) && rb_block_given_p()) {
        return rb_yield(result);
    return result;
match?(string) → true or false click to toggle source
match?(string, offset = 0) → true or false

Returns true or false to indicate whether the regexp is matched or not without updating $~ and other related variables. If the second parameter is present, it specifies the position in the string to begin the search.

/R.../.match?("Ruby")    # => true
/R.../.match?("Ruby", 1) # => false
/P.../.match?("Ruby")    # => false
$&                       # => nil
static VALUE
rb_reg_match_m_p(int argc, VALUE *argv, VALUE re)
    long pos = rb_check_arity(argc, 1, 2) > 1 ? NUM2LONG(argv[1]) : 0;
    return rb_reg_match_p(re, argv[0], pos);
named_captures → hash click to toggle source

Returns a hash representing named captures of self (see Named Captures):

  • Each key is the name of a named capture.

  • Each value is an array of integer indexes for that named capture.


/(?<foo>.)(?<bar>.)/.named_captures # => {"foo"=>[1], "bar"=>[2]}
/(?<foo>.)(?<foo>.)/.named_captures # => {"foo"=>[1, 2]}
/(.)(.)/.named_captures             # => {}
static VALUE
rb_reg_named_captures(VALUE re)
    regex_t *reg = (rb_reg_check(re), RREGEXP_PTR(re));
    VALUE hash = rb_hash_new_with_size(onig_number_of_names(reg));
    onig_foreach_name(reg, reg_named_captures_iter, (void*)hash);
    return hash;
names → array_of_names click to toggle source

Returns an array of names of captures (see Named Captures):

/(?<foo>.)(?<bar>.)(?<baz>.)/.names # => ["foo", "bar", "baz"]
/(?<foo>.)(?<foo>.)/.names          # => ["foo"]
/(.)(.)/.names                      # => []
static VALUE
rb_reg_names(VALUE re)
    VALUE ary;
    ary = rb_ary_new_capa(onig_number_of_names(RREGEXP_PTR(re)));
    onig_foreach_name(RREGEXP_PTR(re), reg_names_iter, (void*)ary);
    return ary;
options → integer click to toggle source

Returns an integer whose bits show the options set in self.

The option bits are:

Regexp::IGNORECASE # => 1
Regexp::EXTENDED   # => 2
Regexp::MULTILINE  # => 4


/foo/.options    # => 0
/foo/i.options   # => 1
/foo/x.options   # => 2
/foo/m.options   # => 4
/foo/mix.options # => 7

Note that additional bits may be set in the returned integer; these are maintained internally in self, are ignored if passed to, and may be ignored by the caller:

Returns the set of bits corresponding to the options used when creating this regexp (see Regexp::new for details). Note that additional bits may be set in the returned options: these are used internally by the regular expression code. These extra bits are ignored if the options are passed to Regexp::new:

r = /\xa1\xa2/e                 # => /\xa1\xa2/
r.source                        # => "\\xa1\\xa2"
r.options                       # => 16, r.options) # => /\xa1\xa2/
static VALUE
rb_reg_options_m(VALUE re)
    int options = rb_reg_options(re);
    return INT2NUM(options);
source → string click to toggle source

Returns the original string of self:

/ab+c/ix.source # => "ab+c"

Regexp escape sequences are retained:

/\x20\+/.source  # => "\\x20\\+"

Lexer escape characters are not retained:

/\//.source  # => "/"
static VALUE
rb_reg_source(VALUE re)
    VALUE str;

    str = rb_str_dup(RREGEXP_SRC(re));
    return str;
timeout → float or nil click to toggle source

It returns the timeout interval for Regexp matching in second. nil means no default timeout configuration.

This configuration is per-object. The global configuration set by Regexp.timeout= is ignored if per-object configuration is set.

re ="^a*b?a*$", timeout: 1)
re.timeout               #=> 1.0
re =~ "a" * 100000 + "x" #=> regexp match timeout (RuntimeError)
static VALUE
rb_reg_timeout_get(VALUE re)
    double d = hrtime2double(RREGEXP_PTR(re)->timelimit);
    if (d == 0.0) return Qnil;
    return DBL2NUM(d);
to_json(*args) click to toggle source

Stores class name (Regexp) with options o and source s (Regexp or String) as JSON string

# File ext/json/lib/json/add/regexp.rb, line 27
def to_json(*args)
to_s → string click to toggle source

Returns a string showing the options and string of self:

r0 = /ab+c/ix
s0 = r0.to_s # => "(?ix-m:ab+c)"

The returned string may be used as an argument to, or as interpolated text for a Regexp literal:

r1 = # => /(?ix-m:ab+c)/
r2 = /#{s0}/        # => /(?ix-m:ab+c)/

Note that r1 and r2 are not equal to r0 because their original strings are different:

r0 == r1  # => false
r0.source # => "ab+c"
r1.source # => "(?ix-m:ab+c)"

Related: Regexp#inspect.

static VALUE
rb_reg_to_s(VALUE re)
    return rb_reg_str_with_term(re, '/');
~ rxp → integer or nil click to toggle source

Equivalent to rxp =~ $_:

$_ = "input data"
~ /at/ # => 7
rb_reg_match2(VALUE re)
    long start;
    VALUE line = rb_lastline_get();

    if (!RB_TYPE_P(line, T_STRING)) {
        return Qnil;

    start = rb_reg_search(re, line, 0, 0);
    if (start < 0) {
        return Qnil;
    start = rb_str_sublen(line, start);
    return LONG2FIX(start);