class Regexp - RDoc Documentation (original) (raw)

A regular expression (also called a regexp) is a match pattern (also simply called a pattern).

A common notation for a regexp uses enclosing slash characters:

/foo/

A regexp may be applied to a target string; The part of the string (if any) that matches the pattern is called a match, and may be said to match:

re = /red/ re.match?('redirect') re.match?('bored')
re.match?('credit')
re.match?('foo')

Regexp Uses

A regexp may be used:

Regexp Objects

A regexp object has:

Creating a Regexp

A regular expression may be created with:

Method match

Each of the methods Regexp#match, String#match, and Symbol#match returns a MatchData object if a match was found, nil otherwise; each also sets global variables:

'food'.match(/foo/) 'food'.match(/bar/)

Operator =~

Each of the operators Regexp#=~, String#=~, and Symbol#=~ returns an integer offset if a match was found, nil otherwise; each also sets global variables:

/bar/ =~ 'foo bar' 'foo bar' =~ /bar/ /baz/ =~ 'foo bar'

Method match?

Each of the methods Regexp#match?, String#match?, and Symbol#match? returns true if a match was found, false otherwise; none sets global variables:

'food'.match?(/foo/) 'food'.match?(/bar/)

Global Variables

Certain regexp-oriented methods assign values to global variables:

The affected global variables are:

Examples:

'foo bar bar baz'.match('bar') $~ $& $` $' $+ $1

/s(\w{2}).*(c)/.match('haystack') $~ $& $` $' $+ $1 $2 $3

'foo'.match('bar') $~ $& $` $' $+ $1

Note that Regexp#match?, String#match?, and Symbol#match? do not set global variables.

Sources

As seen above, the simplest regexp uses a literal expression as its source:

re = /foo/
re.match('food')
re.match('good')

A rich collection of available subexpressions gives the regexp great power and flexibility:

Special Characters

Regexp special characters, called metacharacters, have special meanings in certain contexts; depending on the context, these are sometimes metacharacters:

. ? - + * ^ \ | $ ( ) [ ] { }

To match a metacharacter literally, backslash-escape it:

/o+/.match('foo')

/o+/.match('foo')

To match a backslash literally, backslash-escape it:

/./.match('.')
/\./.match('.')

Method Regexp.escape returns an escaped string:

Regexp.escape('.?-+*^|$()[]{}')

Source Literals

The source literal largely behaves like a double-quoted string; see Double-Quoted String Literals.

In particular, a source literal may contain interpolated expressions:

s = 'foo'
/#{s}/
/#{s.capitalize}/ /#{2 + 2}/

There are differences between an ordinary string literal and a source literal; see Shorthand Character Classes.

Character Classes

A character class is delimited by square brackets; it specifies that certain characters match at a given point in the target string:

re = /B[aeiou]rd/ re.match('Bird') re.match('Bard') re.match('Byrd')

A character class may contain hyphen characters to specify ranges of characters:

/[abcdef]/.match('foo') /[a-f]/.match('foo')
/[a-cd-f]/.match('foo')

When the first character of a character class is a caret (^), the sense of the class is inverted: it matches any character except those specified.

/[^a-eg-z]/.match('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]/

This is equivalent to:

/[abh-w]/

Shorthand Character Classes

Each of the following metacharacters serves as a shorthand for a character class:

Anchors

An anchor is a metasequence that matches a zero-width position between characters in the target string.

For a subexpression with no anchor, matching may begin anywhere in the target string:

/real/.match('surrealist')

For a subexpression with an anchor, matching must begin at the matched anchor.

Boundary Anchors

Each of these anchors matches a boundary:

Lookaround Anchors

Lookahead anchors:

Lookbehind anchors:

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

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

Match-Reset Anchor

Alternation

The vertical bar metacharacter (|) may be used within parentheses to express alternation: two or more subexpressions any of which may match the target string.

Two alternatives:

re = /(a|b)/ re.match('foo') re.match('bar')

Four alternatives:

re = /(a|b|c|d)/ re.match('shazam') re.match('cold')

Each alternative is a subexpression, and may be composed of other subexpressions:

re = /([a-c]|[x-z])/ re.match('bar') re.match('ooz')

Method Regexp.union provides a convenient way to construct a regexp with alternatives.

Quantifiers

A simple regexp matches one character:

/\w/.match('Hello')

An added quantifier specifies how many matches are required or allowed:

Greedy, Lazy, or Possessive Matching

Quantifier matching may be greedy, lazy, or possessive:

More:

Groups and Captures

A simple regexp has (at most) one match:

re = /\d\d\d\d-\d\d-\d\d/ re.match('1943-02-04')
re.match('1943-02-04').size re.match('foo')

Adding one or more pairs of parentheses, (_subexpression_), defines groups, which may result in multiple matched substrings, called captures:

re = /(\d\d\d\d)-(\d\d)-(\d\d)/ re.match('1943-02-04')
re.match('1943-02-04').size

The first capture is the entire matched string; the other captures are the matched substrings from the groups.

A group may have a quantifier:

re = /July 4(th)?/ re.match('July 4')
re.match('July 4th')

re = /(foo)*/ re.match('')
re.match('foo')
re.match('foofoo')

re = /(foo)+/ re.match('')
re.match('foo')
re.match('foofoo')

The returned MatchData object gives access to the matched substrings:

re = /(\d\d\d\d)-(\d\d)-(\d\d)/ md = re.match('1943-02-04')

md[0] md[1] md[2] md[3]

Non-Capturing Groups

A group may be made non-capturing; it is still a group (and, for example, can have a quantifier), but its matching substring is not included among the captures.

A non-capturing group begins with ?: (inside the parentheses):

re = /(?:\d\d\d\d)-(\d\d)-(\d\d)/ md = re.match('1943-02-04')

Backreferences

A group match may also be referenced within the regexp itself; such a reference is called a backreference:

/csh [csh]\1 in/.match('The cat sat in the hat')

This table shows how each subexpression in the regexp above matches a substring in the target string:

Subexpression in Regexp Matching Substring in Target String
First '[csh]' Character 'c'
'(..)' First substring 'at'
First space ' ' First space character ' '
Second '[csh]' Character 's'
'\1' (backreference 'at') Second substring 'at'
' in' Substring ' in'

A regexp may contain any number of groups:

Named Captures

As seen above, a capture can be referred to by its number. A capture can also have a name, prefixed as ?<_name_> or ?'_name_', and the name (symbolized) may be used as an index in MatchData[]:

md = /$(?\d+).(?'cents'\d+)/.match("$3.67")

md[:dollars]
md[:cents]

md[2]

When a regexp contains a named capture, there are no unnamed captures:

/$(?\d+).(\d+)/.match("$3.67")

A named group may be backreferenced as \k<_name_>:

/(?[aeiou]).\k.\k/.match('ototomy')

When (and only when) a regexp contains named capture groups and appears before the =~ operator, the captured substrings are assigned to local variables with corresponding names:

/$(?\d+).(?\d+)/ =~ '$3.67' dollars cents

Method Regexp#named_captures returns a hash of the capture names and substrings; method Regexp#names returns an array of the capture names.

Atomic Grouping

A group may be made atomic with (?>subexpression).

This causes the subexpression to be matched independently of the rest of the expression, so that the matched substring becomes fixed for the remainder of the match, unless the entire subexpression must be abandoned and subsequently revisited.

In this way subexpression is treated as a non-divisible whole. Atomic grouping is typically used to optimise patterns to prevent needless backtracking .

Example (without atomic grouping):

/".*"/.match('"Quote"')

Analysis:

  1. The leading subexpression " in the pattern matches the first character " in the target string.
  2. The next subexpression .* matches the next substring Quote“ (including the trailing double-quote).
  3. Now there is nothing left in the target string to match the trailing subexpression " in the pattern; this would cause the overall match to fail.
  4. The matched substring is backtracked by one position: Quote.
  5. The final subexpression " now matches the final substring ", and the overall match succeeds.

If subexpression .* is grouped atomically, the backtracking is disabled, and the overall match fails:

/"(?>.*)"/.match('"Quote"')

Atomic grouping can affect performance; see Atomic Group.

Subexpression Calls

As seen above, a backreference number (\_n_) or name (\k<_name_>) gives access to a captured substring; the corresponding regexp subexpression may also be accessed, via the number (\g_n_) or name (\g<_name_>):

/\A(?(\g*))*\z/.match('(())')

The pattern:

  1. Matches at the beginning of the string, i.e. before the first character.
  2. Enters a named group paren.
  3. Matches 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 the second character in the string, '('.
  7. Attempts to call paren a third time, but fails because doing so would prevent an overall successful match.
  8. Matches the third character in the string, ')'; marks the end of the second recursive call
  9. Matches the fourth character in the string, ')'.
  10. Matches the end of the string.

See Subexpression calls.

Conditionals

The conditional construct takes the form (?(_cond_)_yes_|_no_), where:

Examples:

re = /\A(foo)?(?(1)(T)|(F))\z/ re.match('fooT') re.match('F')
re.match('fooF') re.match('T')

re = /\A(?foo)?(?()(T)|(F))\z/ re.match('fooT') re.match('F')
re.match('fooF') re.match('T')

Absence Operator

The absence operator is a special group that matches anything which does not match the contained subexpressions.

/(?real)/.match('surrealist') /(?real)ist/.match('surrealist') /sur(?~real)ist/.match('surrealist')

Unicode

Unicode Properties

The /\p{_propertyname_}/ construct (with lowercase p) matches characters using a Unicode property name, much like a character class; property Alpha specifies alphabetic characters:

/\p{Alpha}/.match('a') /\p{Alpha}/.match('1')

A property can be inverted by prefixing the name with a caret character (^):

/\p{^Alpha}/.match('1') /\p{^Alpha}/.match('a')

Or by using \P (uppercase P):

/\P{Alpha}/.match('1') /\P{Alpha}/.match('a')

See Unicode Properties for regexps based on the numerous properties.

Some commonly-used properties correspond to POSIX bracket expressions:

These are also commonly used:

Unicode Character Categories

A Unicode character category name:

Examples:

/\p{lu}/
/\p{LU}/
/\p{Uppercase Letter}/
/\p{Uppercase_Letter}/
/\p{UPPERCASE-LETTER}/

Below are the Unicode character category abbreviations and names. Enumerations of characters in each category are at the links.

Letters:

Marks:

Numbers:

Punctuation:

Unicode Scripts and Blocks

Among the Unicode properties are:

POSIX Bracket Expressions

A POSIX bracket expression is also similar to a character class. These expressions provide a portable alternative to the above, with the added benefit of encompassing non-ASCII characters:

The POSIX bracket expressions:

Ruby also supports these (non-POSIX) bracket expressions:

A comment may be included in a regexp pattern using the (?#comment) construct, where comment is a substring that is to be ignored. arbitrary text ignored by the regexp engine:

/foo(?#Ignore me)bar/.match('foobar')

The comment may not include an unescaped terminator character.

See also Extended Mode.

Modes

Each of these modifiers sets a mode for the regexp:

Any, all, or none of these may be applied.

Modifiers i, m, and x may be applied to subexpressions:

Example:

re = /(?i)te(?-i)st/ re.match('test') re.match('TEst') re.match('TEST') re.match('teST')

re = /t(?i:e)st/ re.match('test') re.match('tEst') re.match('tEST')

Method Regexp#options returns an integer whose value showing the settings for case-insensitivity mode, multiline mode, and extended mode.

Case-Insensitive Mode

By default, a regexp is case-sensitive:

/foo/.match('FOO')

Modifier i enables case-insensitive mode:

/foo/i.match('FOO')

Method Regexp#casefold? returns whether the mode is case-insensitive.

Multiline Mode

The multiline-mode in Ruby is what is commonly called a “dot-all mode”:

Unlike other languages, the modifier m does not affect the anchors ^ and $. These anchors always match at line-boundaries in Ruby.

Extended Mode

Modifier x enables extended mode, which means that:

In extended mode, whitespace and comments may be used to form a self-documented regexp.

Regexp not in extended mode (matches some Roman numerals):

pattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$' re = /#{pattern}/ re.match('MCMXLIII')

Regexp in extended mode:

pattern = <<-EOT ^ # beginning of string M{0,3} # thousands - 0 to 3 Ms (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs), # or 500-800 (D, followed by 0 to 3 Cs) (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs), # or 50-80 (L, followed by 0 to 3 Xs) (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 Is), # or 5-8 (V, followed by 0 to 3 Is) $ # end of string EOT re = /#{pattern}/x re.match('MCMXLIII')

Interpolation Mode

Modifier o means that the first time a literal regexp with interpolations is encountered, the generated Regexp object is saved and used for all future evaluations of that literal regexp. Without modifier o, the generated Regexp is not saved, so each evaluation of the literal regexp generates a new Regexp object.

Without modifier o:

def letters; sleep 5; /[A-Z][a-z]/; end words = %w[abc def xyz] start = Time.now words.each {|word| word.match(/\A[#{letters}]+\z/) } Time.now - start

With modifier o:

start = Time.now words.each {|word| word.match(/\A[#{letters}]+\z/o) } Time.now - start

Note that if the literal regexp does not have interpolations, the o behavior is the default.

Encodings

By default, a regexp with only US-ASCII characters has US-ASCII encoding:

re = /foo/ re.source.encoding re.encoding

A regular expression containing non-US-ASCII characters is assumed to use the source encoding. This can be overridden with one of the following modifiers.

A regexp can be matched against a target string when either:

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

Example:

re = eval("# encoding: ISO-8859-1\n/foo\xff?/") re.encoding
re =~ "foo".encode("UTF-8") re =~ "foo\u0100"

The encoding may be explicitly fixed by including Regexp::FIXEDENCODING in the second argument for Regexp.new:

re = Regexp.new("a".force_encoding('iso-8859-1'), Regexp::FIXEDENCODING) re.encoding

s = "a\u3042" s.encoding
re.match(s)

Timeouts

When either a regexp source or a target string comes from untrusted input, malicious values could become a denial-of-service attack; to prevent such an attack, it is wise to set a timeout.

Regexp has two timeout values:

When regexp.timeout is nil, the timeout “falls through” to Regexp.timeout; when regexp.timeout is non-nil, that value controls timing out:

regexp.timeout Value Regexp.timeout Value Result
nil nil Never times out.
nil Float Times out in Float seconds.
Float Any Times out in Float seconds.

Optimization

For certain values of the pattern and target string, matching time can grow polynomially or exponentially in relation to the input size; the potential vulnerability arising from this is the regular expression denial-of-service (ReDoS) attack.

Regexp matching can apply an optimization to prevent ReDoS attacks. When the optimization is applied, matching time increases linearly (not polynomially or exponentially) in relation to the input size, and a ReDoS attach is not possible.

This optimization is applied if the pattern meets these criteria:

You can use method Regexp.linear_time? to determine whether a pattern meets these criteria:

Regexp.linear_time?(/a*/)
Regexp.linear_time?('a*')
Regexp.linear_time?(/(a*)\1/)

However, an untrusted source may not be safe even if the method returns true, because the optimization uses memoization (which may invoke large memory consumption).

References

Read (online PDF books):

Explore, test (interactive online editor):

Constants

EXTENDED

see Regexp.options and Regexp.new

FIXEDENCODING

see Regexp.options and Regexp.new

IGNORECASE

see Regexp.options and Regexp.new

MULTILINE

see Regexp.options and Regexp.new

NOENCODING

see Regexp.options and Regexp.new

Public Class Methods

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 = Regexp.new(Regexp.escape(s)) r.match(s)

static VALUE rb_reg_s_quote(VALUE c, VALUE str) { return rb_reg_quote(reg_operand(str, TRUE)); }

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'
Regexp.last_match /a/ =~ 'foo'
Regexp.last_match

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

/c(.)t/ =~ 'cat'
Regexp.last_match(0) Regexp.last_match(1) Regexp.last_match(2)

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

Regexp.last_match(-1)

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

/(?\w+)\s*=\s*(?\w+)/ =~ 'var = val' Regexp.last_match
Regexp.last_match(:lhs)
Regexp.last_match('rhs') Regexp.last_match('foo')

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/)

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.

(*1): doi.org/10.1109/SP40001.2021.00032

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 = Regexp.new('foo') r.source
r.options

Optional argument options is one of the following:

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 = Regexp.new('foo', options, timeout: 1.1) r2 = Regexp.new(r)
r2.timeout
r3 = Regexp.new(r, timeout: 3.14)
r3.timeout

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

if (NIL_P(re)) {
    reg_init_args(self, args.str, args.enc, args.flags);
}
else {
    reg_copy(self, re);
}

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 = Regexp.new(Regexp.escape(s)) r.match(s)

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

Regexp.timeout = 1 /^ab?a$/ =~ "a" * 100000 + "x"

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/)

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')

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])
r.match('cat')
r.match('dog')
r.match('cog')

For each pattern that is a string, Regexp.new(pattern) is used:

Regexp.union('penzance')
Regexp.union('a+b*c')
Regexp.union('skiing', 'sledding')
Regexp.union(['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)

Regexp.union([/foo/i, /bar/m, /baz/x])

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/ == Regexp.new('foo')
/foo/ == /foo/i
/foo/ == Regexp.new('food')
/foo/ == Regexp.new("abc".force_encoding("euc-jp"))

regexp === string → true or false click to toggle source

Returns true if self finds a match in string:

/^[a-z]$/ === 'HELLO' /^[A-Z]$/ === 'HELLO'

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

static VALUE rb_reg_eqq(VALUE re, VALUE str) { long start;

str = reg_operand(str, FALSE);
if (NIL_P(str)) {
    rb_backref_set(Qnil);
    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' $~
/ax/ =~ 'input data' $~

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

Example:

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

Assigns nil if not matched:

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

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

r = /(?\w+)\s*=\s*(?\w+)/ r =~ ' x = y ' p foo p bar

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

' x = y ' =~ /(?\w+)\s*=\s*(?\w+)/ p foo, foo

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

r = /(?\w+)/ /(?\w+)\s*=\s*#{r}/ =~ 'x = y' p foo

VALUE 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); }

casefold?→ true or false click to toggle source

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

/a/.casefold?
/a/i.casefold?
/(?i:a)/.casefold?

static VALUE rb_reg_casefold_p(VALUE re) { rb_reg_check(re); return RBOOL(RREGEXP_PTR(re)->options & ONIG_OPTION_IGNORECASE); }

encoding → encoding click to toggle source

Returns the Encoding object that represents the encoding of obj.

VALUE 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/ == Regexp.new('foo')
/foo/ == /foo/i
/foo/ == Regexp.new('food')
/foo/ == Regexp.new("abc".force_encoding("euc-jp"))

VALUE 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/
r.fixed_encoding?
r.match?("\u{6666} a")
r.match?("\xa1\xa2 a".force_encoding("euc-jp")) r.match?("abc".force_encoding("euc-jp"))

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

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

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.

VALUE 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

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(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')
/abra/.match('abracadabra', 4)
/abra/.match('abracadabra', 8)
/abra/.match('abracadabra', 800)

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

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 }

/abra/.match('abracadabra', 4) {|matchdata| p matchdata }

/abra/.match('abracadabra', 8) {|matchdata| p matchdata }

/abra/.match('abracadabra', 8) {|marchdata| fail 'Cannot happen' }

Output (from the first two blocks above):

/(.)(.)(.)/.match("abc")[2] /(.)(.)/.match("abc", 1)[2]

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) {
    rb_backref_set(Qnil);
    return Qnil;
}
rb_match_busy(result);
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")
/R.../.match?("Ruby", 1) /P.../.match?("Ruby")
$&

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):

Examples:

/(?.)(?.)/.named_captures /(?.)(?.)/.named_captures /(.)(.)/.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):

/(?.)(?.)(?.)/.names /(?.)(?.)/.names
/(.)(.)/.names

static VALUE rb_reg_names(VALUE re) { VALUE ary; rb_reg_check(re); 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 Regexp::EXTENDED
Regexp::MULTILINE

Examples:

/foo/.options
/foo/i.options
/foo/x.options
/foo/m.options
/foo/mix.options

Note that additional bits may be set in the returned integer; these are maintained internally in self, are ignored if passed to Regexp.new, 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
r.source
r.options
Regexp.new(r.source, r.options)

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

Regexp escape sequences are retained:

/\x20+/.source

Lexer escape characters are not retained:

///.source

static VALUE rb_reg_source(VALUE re) { VALUE str;

rb_reg_check(re);
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 = Regexp.new("^ab?a$", timeout: 1) re.timeout
re =~ "a" * 100000 + "x"

static VALUE rb_reg_timeout_get(VALUE re) { rb_reg_check(re); double d = hrtime2double(RREGEXP_PTR(re)->timelimit); if (d == 0.0) return Qnil; return DBL2NUM(d); }

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

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

r1 = Regexp.new(s0) r2 = /#{s0}/

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

r0 == r1
r0.source r1.source

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/

VALUE rb_reg_match2(VALUE re) { long start; VALUE line = rb_lastline_get();

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

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

}