File: C:/Ruby27-x64/share/doc/ruby/html/regexp_rdoc.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>regexp - RDoc Documentation</title>
<script type="text/javascript">
var rdoc_rel_prefix = "./";
var index_rel_prefix = "./";
</script>
<script src="./js/navigation.js" defer></script>
<script src="./js/search.js" defer></script>
<script src="./js/search_index.js" defer></script>
<script src="./js/searcher.js" defer></script>
<script src="./js/darkfish.js" defer></script>
<link href="./css/fonts.css" rel="stylesheet">
<link href="./css/rdoc.css" rel="stylesheet">
<body id="top" role="document" class="file">
<nav role="navigation">
<div id="project-navigation">
<div id="home-section" role="region" title="Quick navigation" class="nav-section">
<h2>
<a href="./index.html" rel="home">Home</a>
</h2>
<div id="table-of-contents-navigation">
<a href="./table_of_contents.html#pages">Pages</a>
<a href="./table_of_contents.html#classes">Classes</a>
<a href="./table_of_contents.html#methods">Methods</a>
</div>
</div>
<div id="search-section" role="search" class="project-section initially-hidden">
<form action="#" method="get" accept-charset="utf-8">
<div id="search-field-wrapper">
<input id="search-field" role="combobox" aria-label="Search"
aria-autocomplete="list" aria-controls="search-results"
type="text" name="search" placeholder="Search" spellcheck="false"
title="Type to search, Up and Down to navigate, Enter to load">
</div>
<ul id="search-results" aria-label="Search Results"
aria-busy="false" aria-expanded="false"
aria-atomic="false" class="initially-hidden"></ul>
</form>
</div>
</div>
<div class="nav-section">
<h3>Table of Contents</h3>
<ul class="link-list" role="directory">
<li><a href="#label-3D~+and+Regexp-23match"><code>=~</code> and Regexp#match</a>
<li><a href="#label-3D~+operator"><code>=~</code> operator</a>
<li><a href="#label-Regexp-23match+method">Regexp#match method</a>
<li><a href="#label-Metacharacters+and+Escapes">Metacharacters and Escapes</a>
<li><a href="#label-Character+Classes">Character Classes</a>
<li><a href="#label-Repetition">Repetition</a>
<li><a href="#label-Capturing">Capturing</a>
<li><a href="#label-Grouping">Grouping</a>
<li><a href="#label-Atomic+Grouping">Atomic Grouping</a>
<li><a href="#label-Subexpression+Calls">Subexpression Calls</a>
<li><a href="#label-Alternation">Alternation</a>
<li><a href="#label-Character+Properties">Character Properties</a>
<li><a href="#label-Anchors">Anchors</a>
<li><a href="#label-Options">Options</a>
<li><a href="#label-Free-Spacing+Mode+and+Comments">Free-Spacing Mode and Comments</a>
<li><a href="#label-Encoding">Encoding</a>
<li><a href="#label-Special+global+variables">Special global variables</a>
<li><a href="#label-Performance">Performance</a>
</ul>
</div>
<div id="project-metadata">
<div id="fileindex-section" class="nav-section">
<h3>Pages</h3>
<ul class="link-list">
<li><a href="./CONTRIBUTING_md.html">CONTRIBUTING</a>
<li><a href="./COPYING.html">COPYING</a>
<li><a href="./COPYING_ja.html">COPYING.ja</a>
<li><a href="./LEGAL.html">LEGAL</a>
<li><a href="./NEWS.html">NEWS</a>
<li><a href="./NEWS-1_8_7.html">NEWS-1.8.7</a>
<li><a href="./NEWS-1_9_1.html">NEWS-1.9.1</a>
<li><a href="./NEWS-1_9_2.html">NEWS-1.9.2</a>
<li><a href="./NEWS-1_9_3.html">NEWS-1.9.3</a>
<li><a href="./NEWS-2_0_0.html">NEWS-2.0.0</a>
<li><a href="./NEWS-2_1_0.html">NEWS-2.1.0</a>
<li><a href="./NEWS-2_2_0.html">NEWS-2.2.0</a>
<li><a href="./NEWS-2_3_0.html">NEWS-2.3.0</a>
<li><a href="./NEWS-2_4_0.html">NEWS-2.4.0</a>
<li><a href="./NEWS-2_5_0.html">NEWS-2.5.0</a>
<li><a href="./NEWS-2_6_0.html">NEWS-2.6.0</a>
<li><a href="./README_ja_md.html">README.ja</a>
<li><a href="./README_md.html">README</a>
<li><a href="./bug_triaging_rdoc.html">bug_triaging</a>
<li><a href="./contributing_rdoc.html">contributing</a>
<li><a href="./contributors_rdoc.html">contributors</a>
<li><a href="./dtrace_probes_rdoc.html">dtrace_probes</a>
<li><a href="./extension_ja_rdoc.html">extension.ja</a>
<li><a href="./extension_rdoc.html">extension</a>
<li><a href="./globals_rdoc.html">globals</a>
<li><a href="./keywords_rdoc.html">keywords</a>
<li><a href="./lib/racc/pre-setup.html">pre-setup</a>
<li><a href="./lib/racc/rdoc/grammar_en_rdoc.html">grammar.en</a>
<li><a href="./maintainers_rdoc.html">maintainers</a>
<li><a href="./marshal_rdoc.html">marshal</a>
<li><a href="./regexp_rdoc.html">regexp</a>
<li><a href="./security_rdoc.html">security</a>
<li><a href="./signals_rdoc.html">signals</a>
<li><a href="./standard_library_rdoc.html">standard_library</a>
<li><a href="./syntax_rdoc.html">syntax</a>
<li><a href="./syntax/assignment_rdoc.html">assignment</a>
<li><a href="./syntax/calling_methods_rdoc.html">calling_methods</a>
<li><a href="./syntax/comments_rdoc.html">comments</a>
<li><a href="./syntax/control_expressions_rdoc.html">control_expressions</a>
<li><a href="./syntax/exceptions_rdoc.html">exceptions</a>
<li><a href="./syntax/literals_rdoc.html">literals</a>
<li><a href="./syntax/methods_rdoc.html">methods</a>
<li><a href="./syntax/miscellaneous_rdoc.html">miscellaneous</a>
<li><a href="./syntax/modules_and_classes_rdoc.html">modules_and_classes</a>
<li><a href="./syntax/precedence_rdoc.html">precedence</a>
<li><a href="./syntax/refinements_rdoc.html">refinements</a>
<li><a href="./win32/README_win32.html">README.win32</a>
</ul>
</div>
</div>
</nav>
<main role="main" aria-label="Page regexp.rdoc">
<p>Regular expressions (<em>regexp</em>s) 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 <code>/</code><em>pat</em><code>/</code> and <code>%r{</code><em>pat</em><code>}</code> literals or the <code>Regexp.new</code> constructor.</p>
<p>A regexp is usually delimited with forward slashes (<code>/</code>). For example:</p>
<pre class="ruby"><span class="ruby-regexp">/hay/</span> <span class="ruby-operator">=~</span> <span class="ruby-string">'haystack'</span> <span class="ruby-comment">#=> 0</span>
<span class="ruby-regexp">/y/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'haystack'</span>) <span class="ruby-comment">#=> #<MatchData "y"></span>
</pre>
<p>If a string contains the pattern it is said to <em>match</em>. A literal string matches itself.</p>
<p>Here 'haystack' does not contain the pattern 'needle', so it doesn't match:</p>
<pre class="ruby"><span class="ruby-regexp">/needle/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'haystack'</span>) <span class="ruby-comment">#=> nil</span>
</pre>
<p>Here 'haystack' contains the pattern 'hay', so it matches:</p>
<pre class="ruby"><span class="ruby-regexp">/hay/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'haystack'</span>) <span class="ruby-comment">#=> #<MatchData "hay"></span>
</pre>
<p>Specifically, <code>/st/</code> requires that the string contains the letter <em>s</em> followed by the letter <em>t</em>, so it matches <em>haystack</em>, also.</p>
<h2 id="label-3D~+and+Regexp-23match"><code>=~</code> and <a href="Regexp.html#method-i-match"><code>Regexp#match</code></a><span><a href="#label-3D~+and+Regexp-23match">¶</a> <a href="#top">↑</a></span></h2>
<p>Pattern matching may be achieved by using <code>=~</code> operator or <a href="Regexp.html#method-i-match"><code>Regexp#match</code></a> method.</p>
<h3 id="label-3D~+operator"><code>=~</code> operator<span><a href="#label-3D~+operator">¶</a> <a href="#top">↑</a></span></h3>
<p><code>=~</code> 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 <a href="Regexp.html"><code>Regexp</code></a> and <a href="String.html"><code>String</code></a> so the order of <a href="String.html"><code>String</code></a> and <a href="Regexp.html"><code>Regexp</code></a> do not matter. Other classes may have different implementations of <code>=~</code>.) If a match is found, the operator returns index of first match in string, otherwise it returns <code>nil</code>.</p>
<pre class="ruby"><span class="ruby-regexp">/hay/</span> <span class="ruby-operator">=~</span> <span class="ruby-string">'haystack'</span> <span class="ruby-comment">#=> 0</span>
<span class="ruby-string">'haystack'</span> <span class="ruby-operator">=~</span> <span class="ruby-regexp">/hay/</span> <span class="ruby-comment">#=> 0</span>
<span class="ruby-regexp">/a/</span> <span class="ruby-operator">=~</span> <span class="ruby-string">'haystack'</span> <span class="ruby-comment">#=> 1</span>
<span class="ruby-regexp">/u/</span> <span class="ruby-operator">=~</span> <span class="ruby-string">'haystack'</span> <span class="ruby-comment">#=> nil</span>
</pre>
<p>Using <code>=~</code> operator with a <a href="String.html"><code>String</code></a> and <a href="Regexp.html"><code>Regexp</code></a> the <code>$~</code> global variable is set after a successful match. <code>$~</code> holds a <a href="MatchData.html"><code>MatchData</code></a> object. <a href="Regexp.html#method-c-last_match"><code>Regexp.last_match</code></a> is equivalent to <code>$~</code>.</p>
<h3 id="label-Regexp-23match+method"><a href="Regexp.html#method-i-match"><code>Regexp#match</code></a> method<span><a href="#label-Regexp-23match+method">¶</a> <a href="#top">↑</a></span></h3>
<p>The match method returns a <a href="MatchData.html"><code>MatchData</code></a> object:</p>
<pre class="ruby"><span class="ruby-regexp">/st/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'haystack'</span>) <span class="ruby-comment">#=> #<MatchData "st"></span>
</pre>
<h2 id="label-Metacharacters+and+Escapes">Metacharacters and Escapes<span><a href="#label-Metacharacters+and+Escapes">¶</a> <a href="#top">↑</a></span></h2>
<p>The following are <em>metacharacters</em> <code>(</code>, <code>)</code>, <code>[</code>, <code>]</code>, <code>{</code>, <code>}</code>, <code>.</code>, <code>?</code>, <code>+</code>, <code>*</code>. 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: <code>\\</code>.</p>
<pre class="ruby"><span class="ruby-regexp">/1 \+ 2 = 3\?/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'Does 1 + 2 = 3?'</span>) <span class="ruby-comment">#=> #<MatchData "1 + 2 = 3?"></span>
<span class="ruby-regexp">/a\\\\b/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'a\\\\b'</span>) <span class="ruby-comment">#=> #<MatchData "a\\b"></span>
</pre>
<p>Patterns behave like double-quoted strings and can contain the same backslash escapes (the meaning of <code>\s</code> is different, however, see <a href="#label-Character+Classes">below</a>).</p>
<pre class="ruby"><span class="ruby-regexp">/\s\u{6771 4eac 90fd}/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Go to 東京都"</span>)
<span class="ruby-comment">#=> #<MatchData " 東京都"></span>
</pre>
<p>Arbitrary Ruby expressions can be embedded into patterns with the <code>#{...}</code> construct.</p>
<pre class="ruby"><span class="ruby-identifier">place</span> = <span class="ruby-string">"東京都"</span>
<span class="ruby-regexp">/#{place}/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Go to 東京都"</span>)
<span class="ruby-comment">#=> #<MatchData "東京都"></span>
</pre>
<h2 id="label-Character+Classes">Character Classes<span><a href="#label-Character+Classes">¶</a> <a href="#top">↑</a></span></h2>
<p>A <em>character class</em> is delimited with square brackets (<code>[</code>, <code>]</code>) and lists characters that may appear at that point in the match. <code>/[ab]/</code> means <em>a</em> or <em>b</em>, as opposed to <code>/ab/</code> which means <em>a</em> followed by <em>b</em>.</p>
<pre class="ruby"><span class="ruby-regexp">/W[aeiou]rd/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Word"</span>) <span class="ruby-comment">#=> #<MatchData "Word"></span>
</pre>
<p>Within a character class the hyphen (<code>-</code>) is a metacharacter denoting an inclusive range of characters. <code>[abcd]</code> is equivalent to <code>[a-d]</code>. A range can be followed by another range, so <code>[abcdwxyz]</code> is equivalent to <code>[a-dw-z]</code>. The order in which ranges or individual characters appear inside a character class is irrelevant.</p>
<pre class="ruby"><span class="ruby-regexp">/[0-9a-f]/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'9f'</span>) <span class="ruby-comment">#=> #<MatchData "9"></span>
<span class="ruby-regexp">/[9f]/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'9f'</span>) <span class="ruby-comment">#=> #<MatchData "9"></span>
</pre>
<p>If the first character of a character class is a caret (<code>^</code>) the class is inverted: it matches any character <em>except</em> those named.</p>
<pre class="ruby"><span class="ruby-regexp">/[^a-eg-z]/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'f'</span>) <span class="ruby-comment">#=> #<MatchData "f"></span>
</pre>
<p>A character class may contain another character class. By itself this isn't useful because <code>[a-z[0-9]]</code> describes the same set as <code>[a-z0-9]</code>. However, character classes also support the <code>&&</code> operator which performs set intersection on its arguments. The two can be combined as follows:</p>
<pre class="ruby"><span class="ruby-regexp">/[a-w&&[^c-g]z]/</span> <span class="ruby-comment"># ([a-w] AND ([^c-g] OR z))</span>
</pre>
<p>This is equivalent to:</p>
<pre class="ruby"><span class="ruby-regexp">/[abh-w]/</span>
</pre>
<p>The following metacharacters also behave like character classes:</p>
<ul><li>
<p><code>/./</code> - Any character except a newline.</p>
</li><li>
<p><code>/./m</code> - Any character (the <code>m</code> modifier enables multiline mode)</p>
</li><li>
<p><code>/\w/</code> - A word character (<code>[a-zA-Z0-9_]</code>)</p>
</li><li>
<p><code>/\W/</code> - A non-word character (<code>[^a-zA-Z0-9_]</code>). Please take a look at <a href="https://bugs.ruby-lang.org/issues/4044">Bug #4044</a> if using <code>/\W/</code> with the <code>/i</code> modifier.</p>
</li><li>
<p><code>/\d/</code> - A digit character (<code>[0-9]</code>)</p>
</li><li>
<p><code>/\D/</code> - A non-digit character (<code>[^0-9]</code>)</p>
</li><li>
<p><code>/\h/</code> - A hexdigit character (<code>[0-9a-fA-F]</code>)</p>
</li><li>
<p><code>/\H/</code> - A non-hexdigit character (<code>[^0-9a-fA-F]</code>)</p>
</li><li>
<p><code>/\s/</code> - A whitespace character: <code>/[ \t\r\n\f\v]/</code></p>
</li><li>
<p><code>/\S/</code> - A non-whitespace character: <code>/[^ \t\r\n\f\v]/</code></p>
</li><li>
<p><code>/\R/</code> - A linebreak: <code>\n</code>, <code>\v</code>, <code>\f</code>, <code>\r</code> <code>\u0085</code> (NEXT LINE), <code>\u2028</code> (LINE SEPARATOR), <code>\u2029</code> (PARAGRAPH SEPARATOR) or <code>\r\n</code>.</p>
</li></ul>
<p>POSIX <em>bracket expressions</em> 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, <code>/\d/</code> matches only the ASCII decimal digits (0-9); whereas <code>/[[:digit:]]/</code> matches any character in the Unicode <em>Nd</em> category.</p>
<ul><li>
<p><code>/[[:alnum:]]/</code> - Alphabetic and numeric character</p>
</li><li>
<p><code>/[[:alpha:]]/</code> - Alphabetic character</p>
</li><li>
<p><code>/[[:blank:]]/</code> - Space or tab</p>
</li><li>
<p><code>/[[:cntrl:]]/</code> - Control character</p>
</li><li>
<p><code>/[[:digit:]]/</code> - Digit</p>
</li><li>
<p><code>/[[:graph:]]/</code> - Non-blank character (excludes spaces, control characters, and similar)</p>
</li><li>
<p><code>/[[:lower:]]/</code> - Lowercase alphabetical character</p>
</li><li>
<p><code>/[[:print:]]/</code> - Like [:graph:], but includes the space character</p>
</li><li>
<p><code>/[[:punct:]]/</code> - Punctuation character</p>
</li><li>
<p><code>/[[:space:]]/</code> - Whitespace character (<code>[:blank:]</code>, newline, carriage return, etc.)</p>
</li><li>
<p><code>/[[:upper:]]/</code> - Uppercase alphabetical</p>
</li><li>
<p><code>/[[:xdigit:]]/</code> - Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F)</p>
</li></ul>
<p>Ruby also supports the following non-POSIX character classes:</p>
<ul><li>
<p><code>/[[:word:]]/</code> - A character in one of the following Unicode general categories <em>Letter</em>, <em>Mark</em>, <em>Number</em>, <em>Connector_Punctuation</em></p>
</li><li>
<p><code>/[[:ascii:]]/</code> - A character in the ASCII character set</p>
<pre class="ruby"><span class="ruby-comment"># U+06F2 is "EXTENDED ARABIC-INDIC DIGIT TWO"</span>
<span class="ruby-regexp">/[[:digit:]]/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"\u06F2"</span>) <span class="ruby-comment">#=> #<MatchData "\u{06F2}"></span>
<span class="ruby-regexp">/[[:upper:]][[:lower:]]/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Hello"</span>) <span class="ruby-comment">#=> #<MatchData "He"></span>
<span class="ruby-regexp">/[[:xdigit:]][[:xdigit:]]/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"A6"</span>) <span class="ruby-comment">#=> #<MatchData "A6"></span>
</pre>
</li></ul>
<h2 id="label-Repetition">Repetition<span><a href="#label-Repetition">¶</a> <a href="#top">↑</a></span></h2>
<p>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 <em>quantifiers</em>.</p>
<ul><li>
<p><code>*</code> - Zero or more times</p>
</li><li>
<p><code>+</code> - One or more times</p>
</li><li>
<p><code>?</code> - Zero or one times (optional)</p>
</li><li>
<p><code>{</code><em>n</em><code>}</code> - Exactly <em>n</em> times</p>
</li><li>
<p><code>{</code><em>n</em><code>,}</code> - <em>n</em> or more times</p>
</li><li>
<p><code>{,</code><em>m</em><code>}</code> - <em>m</em> or less times</p>
</li><li>
<p><code>{</code><em>n</em><code>,</code><em>m</em><code>}</code> - At least <em>n</em> and at most <em>m</em> times</p>
</li></ul>
<p>At least one uppercase character ('H'), at least one lowercase character ('e'), two 'l' characters, then one 'o':</p>
<pre class="ruby"><span class="ruby-string">"Hello"</span>.<span class="ruby-identifier">match</span>(<span class="ruby-regexp">/[[:upper:]]+[[:lower:]]+l{2}o/</span>) <span class="ruby-comment">#=> #<MatchData "Hello"></span>
</pre>
<p>Repetition is <em>greedy</em> by default: as many occurrences as possible are matched while still allowing the overall match to succeed. By contrast, <em>lazy</em> matching makes the minimal amount of matches necessary for overall success. Most greedy metacharacters can be made lazy by following them with <code>?</code>. For the <code>{n}</code> pattern, because it specifies an exact number of characters to match and not a variable number of characters, the <code>?</code> metacharacter instead makes the repeated pattern optional.</p>
<p>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>':</p>
<pre class="ruby"><span class="ruby-regexp">/<.+>/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"<a><b>"</span>) <span class="ruby-comment">#=> #<MatchData "<a><b>"></span>
<span class="ruby-regexp">/<.+?>/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"<a><b>"</span>) <span class="ruby-comment">#=> #<MatchData "<a>"></span>
</pre>
<p>A quantifier followed by <code>+</code> matches <em>possessively</em>: 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.</p>
<h2 id="label-Capturing">Capturing<span><a href="#label-Capturing">¶</a> <a href="#top">↑</a></span></h2>
<p>Parentheses can be used for <em>capturing</em>. The text enclosed by the <em>n</em><sup>th</sup> group of parentheses can be subsequently referred to with <em>n</em>. Within a pattern use the <em>backreference</em> <code>\n</code>; outside of the pattern use <code>MatchData[n]</code>.</p>
<p>'at' is captured by the first group of parentheses, then referred to later with <code>\1</code>:</p>
<pre class="ruby"><span class="ruby-regexp">/[csh](..) [csh]\1 in/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"The cat sat in the hat"</span>)
<span class="ruby-comment">#=> #<MatchData "cat sat in" 1:"at"></span>
</pre>
<p><a href="Regexp.html#method-i-match"><code>Regexp#match</code></a> returns a <a href="MatchData.html"><code>MatchData</code></a> object which makes the captured text available with its [] method:</p>
<pre class="ruby"><span class="ruby-regexp">/[csh](..) [csh]\1 in/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"The cat sat in the hat"</span>)[<span class="ruby-value">1</span>] <span class="ruby-comment">#=> 'at'</span>
</pre>
<p>Capture groups can be referred to by name when defined with the <code>(?<</code><em>name</em><code>>)</code> or <code>(?'</code><em>name</em><code>')</code> constructs.</p>
<pre class="ruby"><span class="ruby-regexp">/\$(?<dollars>\d+)\.(?<cents>\d+)/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"$3.67"</span>)
<span class="ruby-comment">#=> #<MatchData "$3.67" dollars:"3" cents:"67"></span>
<span class="ruby-regexp">/\$(?<dollars>\d+)\.(?<cents>\d+)/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"$3.67"</span>)[<span class="ruby-value">:dollars</span>] <span class="ruby-comment">#=> "3"</span>
</pre>
<p>Named groups can be backreferenced with <code>\k<</code><em>name</em><code>></code>, where <em>name</em> is the group name.</p>
<pre class="ruby"><span class="ruby-regexp">/(?<vowel>[aeiou]).\k<vowel>.\k<vowel>/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'ototomy'</span>)
<span class="ruby-comment">#=> #<MatchData "ototo" vowel:"o"></span>
</pre>
<p><strong>Note</strong>: 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.</p>
<pre class="ruby"><span class="ruby-regexp">/(\w)(\w)/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"ab"</span>).<span class="ruby-identifier">captures</span> <span class="ruby-comment"># => ["a", "b"]</span>
<span class="ruby-regexp">/(\w)(\w)/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"ab"</span>).<span class="ruby-identifier">named_captures</span> <span class="ruby-comment"># => {}</span>
<span class="ruby-regexp">/(?<c>\w)(\w)/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"ab"</span>).<span class="ruby-identifier">captures</span> <span class="ruby-comment"># => ["a"]</span>
<span class="ruby-regexp">/(?<c>\w)(\w)/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"ab"</span>).<span class="ruby-identifier">named_captures</span> <span class="ruby-comment"># => {"c"=>"a"}</span>
</pre>
<p>When named capture groups are used with a literal regexp on the left-hand side of an expression and the <code>=~</code> operator, the captured text is also assigned to local variables with corresponding names.</p>
<pre class="ruby"><span class="ruby-regexp">/\$(?<dollars>\d+)\.(?<cents>\d+)/</span> <span class="ruby-operator">=~</span> <span class="ruby-string">"$3.67"</span> <span class="ruby-comment">#=> 0</span>
<span class="ruby-identifier">dollars</span> <span class="ruby-comment">#=> "3"</span>
</pre>
<h2 id="label-Grouping">Grouping<span><a href="#label-Grouping">¶</a> <a href="#top">↑</a></span></h2>
<p>Parentheses also <em>group</em> the terms they enclose, allowing them to be quantified as one <em>atomic</em> whole.</p>
<p>The pattern below matches a vowel followed by 2 word characters:</p>
<pre class="ruby"><span class="ruby-regexp">/[aeiou]\w{2}/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Caenorhabditis elegans"</span>) <span class="ruby-comment">#=> #<MatchData "aen"></span>
</pre>
<p>Whereas the following pattern matches a vowel followed by a word character, twice, i.e. <code>[aeiou]\w[aeiou]\w</code>: 'enor'.</p>
<pre class="ruby"><span class="ruby-regexp">/([aeiou]\w){2}/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Caenorhabditis elegans"</span>)
<span class="ruby-comment">#=> #<MatchData "enor" 1:"or"></span>
</pre>
<p>The <code>(?:</code>…<code>)</code> 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.</p>
<p>The first group of parentheses captures 'n' and the second 'ti'. The second group is referred to later with the backreference <code>\2</code>:</p>
<pre class="ruby"><span class="ruby-regexp">/I(n)ves(ti)ga\2ons/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Investigations"</span>)
<span class="ruby-comment">#=> #<MatchData "Investigations" 1:"n" 2:"ti"></span>
</pre>
<p>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 <code>\1</code> now refers to 'ti'.</p>
<pre class="ruby"><span class="ruby-regexp">/I(?:n)ves(ti)ga\1ons/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Investigations"</span>)
<span class="ruby-comment">#=> #<MatchData "Investigations" 1:"ti"></span>
</pre>
<h3 id="label-Atomic+Grouping">Atomic Grouping<span><a href="#label-Atomic+Grouping">¶</a> <a href="#top">↑</a></span></h3>
<p>Grouping can be made <em>atomic</em> with <code>(?></code><em>pat</em><code>)</code>. This causes the subexpression <em>pat</em> 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 <em>pat</em> 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.</p>
<p>The <code>"</code> in the pattern below matches the first character of the string, then <code>.*</code> matches <em>Quote“</em>. This causes the overall match to fail, so the text matched by <code>.*</code> is backtracked by one position, which leaves the final character of the string available to match <code>"</code></p>
<pre class="ruby"><span class="ruby-regexp">/".*"/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'"Quote"'</span>) <span class="ruby-comment">#=> #<MatchData "\"Quote\""></span>
</pre>
<p>If <code>.*</code> is grouped atomically, it refuses to backtrack <em>Quote“</em>, even though this means that the overall match fails</p>
<pre class="ruby"><span class="ruby-regexp">/"(?>.*)"/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'"Quote"'</span>) <span class="ruby-comment">#=> nil</span>
</pre>
<h2 id="label-Subexpression+Calls">Subexpression Calls<span><a href="#label-Subexpression+Calls">¶</a> <a href="#top">↑</a></span></h2>
<p>The <code>\g<</code><em>name</em><code>></code> syntax matches the previous subexpression named <em>name</em>, 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.</p>
<p>This pattern matches a <em>(</em> character and assigns it to the <code>paren</code> group, tries to call that the <code>paren</code> sub-expression again but fails, then matches a literal <em>)</em>:</p>
<pre class="ruby"><span class="ruby-regexp">/\A(?<paren>\(\g<paren>*\))*\z/</span> <span class="ruby-operator">=~</span> <span class="ruby-string">'()'</span>
<span class="ruby-regexp">/\A(?<paren>\(\g<paren>*\))*\z/</span> <span class="ruby-operator">=~</span> <span class="ruby-string">'(())'</span> <span class="ruby-comment">#=> 0</span>
<span class="ruby-comment"># ^1</span>
<span class="ruby-comment"># ^2</span>
<span class="ruby-comment"># ^3</span>
<span class="ruby-comment"># ^4</span>
<span class="ruby-comment"># ^5</span>
<span class="ruby-comment"># ^6</span>
<span class="ruby-comment"># ^7</span>
<span class="ruby-comment"># ^8</span>
<span class="ruby-comment"># ^9</span>
<span class="ruby-comment"># ^10</span>
</pre>
<ol><li>
<p>Matches at the beginning of the string, i.e. before the first character.</p>
</li><li>
<p>Enters a named capture group called <code>paren</code></p>
</li><li>
<p>Matches a literal <em>(</em>, the first character in the string</p>
</li><li>
<p>Calls the <code>paren</code> group again, i.e. recurses back to the second step</p>
</li><li>
<p>Re-enters the <code>paren</code> group</p>
</li><li>
<p>Matches a literal <em>(</em>, the second character in the string</p>
</li><li>
<p>Try to call <code>paren</code> a third time, but fail because doing so would prevent an overall successful match</p>
</li><li>
<p>Match a literal <em>)</em>, the third character in the string. Marks the end of the second recursive call</p>
</li><li>
<p>Match a literal <em>)</em>, the fourth character in the string</p>
</li><li>
<p>Match the end of the string</p>
</li></ol>
<h2 id="label-Alternation">Alternation<span><a href="#label-Alternation">¶</a> <a href="#top">↑</a></span></h2>
<p>The vertical bar metacharacter (<code>|</code>) combines two expressions into a single one that matches either of the expressions. Each expression is an <em>alternative</em>.</p>
<pre class="ruby"><span class="ruby-regexp">/\w(and|or)\w/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Feliformia"</span>) <span class="ruby-comment">#=> #<MatchData "form" 1:"or"></span>
<span class="ruby-regexp">/\w(and|or)\w/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"furandi"</span>) <span class="ruby-comment">#=> #<MatchData "randi" 1:"and"></span>
<span class="ruby-regexp">/\w(and|or)\w/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"dissemblance"</span>) <span class="ruby-comment">#=> nil</span>
</pre>
<h2 id="label-Character+Properties">Character Properties<span><a href="#label-Character+Properties">¶</a> <a href="#top">↑</a></span></h2>
<p>The <code>\p{}</code> construct matches characters with the named property, much like POSIX bracket classes.</p>
<ul><li>
<p><code>/\p{Alnum}/</code> - Alphabetic and numeric character</p>
</li><li>
<p><code>/\p{Alpha}/</code> - Alphabetic character</p>
</li><li>
<p><code>/\p{Blank}/</code> - Space or tab</p>
</li><li>
<p><code>/\p{Cntrl}/</code> - Control character</p>
</li><li>
<p><code>/\p{Digit}/</code> - Digit</p>
</li><li>
<p><code>/\p{Graph}/</code> - Non-blank character (excludes spaces, control characters, and similar)</p>
</li><li>
<p><code>/\p{Lower}/</code> - Lowercase alphabetical character</p>
</li><li>
<p><code>/\p{Print}/</code> - Like <code>\p{Graph}</code>, but includes the space character</p>
</li><li>
<p><code>/\p{Punct}/</code> - Punctuation character</p>
</li><li>
<p><code>/\p{Space}/</code> - Whitespace character (<code>[:blank:]</code>, newline, carriage return, etc.)</p>
</li><li>
<p><code>/\p{Upper}/</code> - Uppercase alphabetical</p>
</li><li>
<p><code>/\p{XDigit}/</code> - Digit allowed in a hexadecimal number (i.e., 0-9a-fA-F)</p>
</li><li>
<p><code>/\p{Word}/</code> - A member of one of the following Unicode general category <em>Letter</em>, <em>Mark</em>, <em>Number</em>, <em>Connector_Punctuation</em></p>
</li><li>
<p><code>/\p{ASCII}/</code> - A character in the ASCII character set</p>
</li><li>
<p><code>/\p{Any}/</code> - Any Unicode character (including unassigned characters)</p>
</li><li>
<p><code>/\p{Assigned}/</code> - An assigned character</p>
</li></ul>
<p>A Unicode character's <em>General Category</em> value can also be matched with <code>\p{</code><em>Ab</em><code>}</code> where <em>Ab</em> is the category's abbreviation as described below:</p>
<ul><li>
<p><code>/\p{L}/</code> - 'Letter'</p>
</li><li>
<p><code>/\p{Ll}/</code> - 'Letter: Lowercase'</p>
</li><li>
<p><code>/\p{Lm}/</code> - 'Letter: Mark'</p>
</li><li>
<p><code>/\p{Lo}/</code> - 'Letter: Other'</p>
</li><li>
<p><code>/\p{Lt}/</code> - 'Letter: Titlecase'</p>
</li><li>
<p><code>/\p{Lu}/</code> - 'Letter: Uppercase</p>
</li><li>
<p><code>/\p{Lo}/</code> - 'Letter: Other'</p>
</li><li>
<p><code>/\p{M}/</code> - 'Mark'</p>
</li><li>
<p><code>/\p{Mn}/</code> - 'Mark: Nonspacing'</p>
</li><li>
<p><code>/\p{Mc}/</code> - 'Mark: Spacing Combining'</p>
</li><li>
<p><code>/\p{Me}/</code> - 'Mark: Enclosing'</p>
</li><li>
<p><code>/\p{N}/</code> - 'Number'</p>
</li><li>
<p><code>/\p{Nd}/</code> - 'Number: Decimal Digit'</p>
</li><li>
<p><code>/\p{Nl}/</code> - 'Number: Letter'</p>
</li><li>
<p><code>/\p{No}/</code> - 'Number: Other'</p>
</li><li>
<p><code>/\p{P}/</code> - 'Punctuation'</p>
</li><li>
<p><code>/\p{Pc}/</code> - 'Punctuation: Connector'</p>
</li><li>
<p><code>/\p{Pd}/</code> - 'Punctuation: Dash'</p>
</li><li>
<p><code>/\p{Ps}/</code> - 'Punctuation: Open'</p>
</li><li>
<p><code>/\p{Pe}/</code> - 'Punctuation: Close'</p>
</li><li>
<p><code>/\p{Pi}/</code> - 'Punctuation: Initial Quote'</p>
</li><li>
<p><code>/\p{Pf}/</code> - 'Punctuation: Final Quote'</p>
</li><li>
<p><code>/\p{Po}/</code> - 'Punctuation: Other'</p>
</li><li>
<p><code>/\p{S}/</code> - 'Symbol'</p>
</li><li>
<p><code>/\p{Sm}/</code> - 'Symbol: Math'</p>
</li><li>
<p><code>/\p{Sc}/</code> - 'Symbol: Currency'</p>
</li><li>
<p><code>/\p{Sc}/</code> - 'Symbol: Currency'</p>
</li><li>
<p><code>/\p{Sk}/</code> - 'Symbol: Modifier'</p>
</li><li>
<p><code>/\p{So}/</code> - 'Symbol: Other'</p>
</li><li>
<p><code>/\p{Z}/</code> - 'Separator'</p>
</li><li>
<p><code>/\p{Zs}/</code> - 'Separator: Space'</p>
</li><li>
<p><code>/\p{Zl}/</code> - 'Separator: Line'</p>
</li><li>
<p><code>/\p{Zp}/</code> - 'Separator: Paragraph'</p>
</li><li>
<p><code>/\p{C}/</code> - 'Other'</p>
</li><li>
<p><code>/\p{Cc}/</code> - 'Other: Control'</p>
</li><li>
<p><code>/\p{Cf}/</code> - 'Other: Format'</p>
</li><li>
<p><code>/\p{Cn}/</code> - 'Other: Not Assigned'</p>
</li><li>
<p><code>/\p{Co}/</code> - 'Other: Private Use'</p>
</li><li>
<p><code>/\p{Cs}/</code> - 'Other: Surrogate'</p>
</li></ul>
<p>Lastly, <code>\p{}</code> matches a character's Unicode <em>script</em>. The following scripts are supported: <em>Arabic</em>, <em>Armenian</em>, <em>Balinese</em>, <em>Bengali</em>, <em>Bopomofo</em>, <em>Braille</em>, <em>Buginese</em>, <em>Buhid</em>, <em>Canadian_Aboriginal</em>, <em>Carian</em>, <em>Cham</em>, <em>Cherokee</em>, <em>Common</em>, <em>Coptic</em>, <em>Cuneiform</em>, <em>Cypriot</em>, <em>Cyrillic</em>, <em>Deseret</em>, <em>Devanagari</em>, <em>Ethiopic</em>, <em>Georgian</em>, <em>Glagolitic</em>, <em>Gothic</em>, <em>Greek</em>, <em>Gujarati</em>, <em>Gurmukhi</em>, <em>Han</em>, <em>Hangul</em>, <em>Hanunoo</em>, <em>Hebrew</em>, <em>Hiragana</em>, <em>Inherited</em>, <em>Kannada</em>, <em>Katakana</em>, <em>Kayah_Li</em>, <em>Kharoshthi</em>, <em>Khmer</em>, <em>Lao</em>, <em>Latin</em>, <em>Lepcha</em>, <em>Limbu</em>, <em>Linear_B</em>, <em>Lycian</em>, <em>Lydian</em>, <em>Malayalam</em>, <em>Mongolian</em>, <em>Myanmar</em>, <em>New_Tai_Lue</em>, <em>Nko</em>, <em>Ogham</em>, <em>Ol_Chiki</em>, <em>Old_Italic</em>, <em>Old_Persian</em>, <em>Oriya</em>, <em>Osmanya</em>, <em>Phags_Pa</em>, <em>Phoenician</em>, <em>Rejang</em>, <em>Runic</em>, <em>Saurashtra</em>, <em>Shavian</em>, <em>Sinhala</em>, <em>Sundanese</em>, <em>Syloti_Nagri</em>, <em>Syriac</em>, <em>Tagalog</em>, <em>Tagbanwa</em>, <em>Tai_Le</em>, <em>Tamil</em>, <em>Telugu</em>, <em>Thaana</em>, <em>Thai</em>, <em>Tibetan</em>, <em>Tifinagh</em>, <em>Ugaritic</em>, <em>Vai</em>, and <em>Yi</em>.</p>
<p>Unicode codepoint U+06E9 is named “ARABIC PLACE OF SAJDAH” and belongs to the Arabic script:</p>
<pre class="ruby"><span class="ruby-regexp">/\p{Arabic}/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"\u06E9"</span>) <span class="ruby-comment">#=> #<MatchData "\u06E9"></span>
</pre>
<p>All character properties can be inverted by prefixing their name with a caret (<code>^</code>).</p>
<p>Letter 'A' is not in the Unicode Ll (Letter; Lowercase) category, so this match succeeds:</p>
<pre class="ruby"><span class="ruby-regexp">/\p{^Ll}/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"A"</span>) <span class="ruby-comment">#=> #<MatchData "A"></span>
</pre>
<h2 id="label-Anchors">Anchors<span><a href="#label-Anchors">¶</a> <a href="#top">↑</a></span></h2>
<p>Anchors are metacharacter that match the zero-width positions between characters, <em>anchoring</em> the match to a specific position.</p>
<ul><li>
<p><code>^</code> - Matches beginning of line</p>
</li><li>
<p><code>$</code> - Matches end of line</p>
</li><li>
<p><code>\A</code> - Matches beginning of string.</p>
</li><li>
<p><code>\Z</code> - Matches end of string. If string ends with a newline, it matches just before newline</p>
</li><li>
<p><code>\z</code> - Matches end of string</p>
</li><li>
<p><code>\G</code> - Matches first matching position:</p>
<p>In methods like <code>String#gsub</code> and <code>String#scan</code>, it changes on each iteration. It initially matches the beginning of subject, and in each following iteration it matches where the last match finished.</p>
<pre class="ruby"><span class="ruby-string">" a b c"</span>.<span class="ruby-identifier">gsub</span>(<span class="ruby-regexp">/ /</span>, <span class="ruby-string">'_'</span>) <span class="ruby-comment">#=> "____a_b_c"</span>
<span class="ruby-string">" a b c"</span>.<span class="ruby-identifier">gsub</span>(<span class="ruby-regexp">/\G /</span>, <span class="ruby-string">'_'</span>) <span class="ruby-comment">#=> "____a b c"</span>
</pre>
<p>In methods like <code>Regexp#match</code> and <code>String#match</code> that take an (optional) offset, it matches where the search begins.</p>
<pre class="ruby"><span class="ruby-string">"hello, world"</span>.<span class="ruby-identifier">match</span>(<span class="ruby-regexp">/,/</span>, <span class="ruby-value">3</span>) <span class="ruby-comment">#=> #<MatchData ","></span>
<span class="ruby-string">"hello, world"</span>.<span class="ruby-identifier">match</span>(<span class="ruby-regexp">/\G,/</span>, <span class="ruby-value">3</span>) <span class="ruby-comment">#=> nil</span>
</pre>
</li><li>
<p><code>\b</code> - Matches word boundaries when outside brackets; backspace (0x08) when inside brackets</p>
</li><li>
<p><code>\B</code> - Matches non-word boundaries</p>
</li><li>
<p><code>(?=</code><em>pat</em><code>)</code> - <em>Positive lookahead</em> assertion: ensures that the following characters match <em>pat</em>, but doesn't include those characters in the matched text</p>
</li><li>
<p><code>(?!</code><em>pat</em><code>)</code> - <em>Negative lookahead</em> assertion: ensures that the following characters do not match <em>pat</em>, but doesn't include those characters in the matched text</p>
</li><li>
<p><code>(?<=</code><em>pat</em><code>)</code> - <em>Positive lookbehind</em> assertion: ensures that the preceding characters match <em>pat</em>, but doesn't include those characters in the matched text</p>
</li><li>
<p><code>(?<!</code><em>pat</em><code>)</code> - <em>Negative lookbehind</em> assertion: ensures that the preceding characters do not match <em>pat</em>, but doesn't include those characters in the matched text</p>
</li></ul>
<p>If a pattern isn't anchored it can begin at any point in the string:</p>
<pre class="ruby"><span class="ruby-regexp">/real/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"surrealist"</span>) <span class="ruby-comment">#=> #<MatchData "real"></span>
</pre>
<p>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:</p>
<pre class="ruby"><span class="ruby-regexp">/\Areal/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"surrealist"</span>) <span class="ruby-comment">#=> nil</span>
</pre>
<p>The match below fails because although 'Demand' contains 'and', the pattern does not occur at a word boundary.</p>
<pre class="ruby"><span class="ruby-regexp">/\band/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Demand"</span>)
</pre>
<p>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:</p>
<pre class="ruby"><span class="ruby-regexp">/\Band.+/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Supply and demand curve"</span>) <span class="ruby-comment">#=> #<MatchData "and curve"></span>
</pre>
<p>The pattern below uses positive lookahead and positive lookbehind to match text appearing in tags without including the tags in the match:</p>
<pre class="ruby"><span class="ruby-regexp">/(?<=<b>)\w+(?=<\/b>)/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">"Fortune favours the <b>bold</b>"</span>)
<span class="ruby-comment">#=> #<MatchData "bold"></span>
</pre>
<h2 id="label-Options">Options<span><a href="#label-Options">¶</a> <a href="#top">↑</a></span></h2>
<p>The end delimiter for a regexp can be followed by one or more single-letter options which control how the pattern can match.</p>
<ul><li>
<p><code>/pat/i</code> - Ignore case</p>
</li><li>
<p><code>/pat/m</code> - Treat a newline as a character matched by <code>.</code></p>
</li><li>
<p><code>/pat/x</code> - Ignore whitespace and comments in the pattern</p>
</li><li>
<p><code>/pat/o</code> - Perform <code>#{}</code> interpolation only once</p>
</li></ul>
<p><code>i</code>, <code>m</code>, and <code>x</code> can also be applied on the subexpression level with the <code>(?</code><em>on</em><code>-</code><em>off</em><code>)</code> construct, which enables options <em>on</em>, and disables options <em>off</em> for the expression enclosed by the parentheses:</p>
<pre class="ruby"><span class="ruby-regexp">/a(?i:b)c/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'aBc'</span>) <span class="ruby-comment">#=> #<MatchData "aBc"></span>
<span class="ruby-regexp">/a(?-i:b)c/i</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'ABC'</span>) <span class="ruby-comment">#=> nil</span>
</pre>
<p>Additionally, these options can also be toggled for the remainder of the pattern:</p>
<pre class="ruby"><span class="ruby-regexp">/a(?i)bc/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'abC'</span>) <span class="ruby-comment">#=> #<MatchData "abC"></span>
</pre>
<p>Options may also be used with <code>Regexp.new</code>:</p>
<pre class="ruby"><span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">new</span>(<span class="ruby-string">"abc"</span>, <span class="ruby-constant">Regexp</span><span class="ruby-operator">::</span><span class="ruby-constant">IGNORECASE</span>) <span class="ruby-comment">#=> /abc/i</span>
<span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">new</span>(<span class="ruby-string">"abc"</span>, <span class="ruby-constant">Regexp</span><span class="ruby-operator">::</span><span class="ruby-constant">MULTILINE</span>) <span class="ruby-comment">#=> /abc/m</span>
<span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">new</span>(<span class="ruby-string">"abc # Comment"</span>, <span class="ruby-constant">Regexp</span><span class="ruby-operator">::</span><span class="ruby-constant">EXTENDED</span>) <span class="ruby-comment">#=> /abc # Comment/x</span>
<span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">new</span>(<span class="ruby-string">"abc"</span>, <span class="ruby-constant">Regexp</span><span class="ruby-operator">::</span><span class="ruby-constant">IGNORECASE</span> <span class="ruby-operator">|</span> <span class="ruby-constant">Regexp</span><span class="ruby-operator">::</span><span class="ruby-constant">MULTILINE</span>) <span class="ruby-comment">#=> /abc/mi</span>
</pre>
<h2 id="label-Free-Spacing+Mode+and+Comments">Free-Spacing Mode and Comments<span><a href="#label-Free-Spacing+Mode+and+Comments">¶</a> <a href="#top">↑</a></span></h2>
<p>As mentioned above, the <code>x</code> option enables <em>free-spacing</em> mode. Literal white space inside the pattern is ignored, and the octothorpe (<code>#</code>) 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.</p>
<p>A contrived pattern to match a number with optional decimal places:</p>
<pre class="ruby"><span class="ruby-identifier">float_pat</span> = <span class="ruby-regexp">/\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
\Z/x</span>
<span class="ruby-identifier">float_pat</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'3.14'</span>) <span class="ruby-comment">#=> #<MatchData "3.14" 1:".14"></span>
</pre>
<p>There are a number of strategies for matching whitespace:</p>
<ul><li>
<p>Use a pattern such as <code>\s</code> or <code>\p{Space}</code>.</p>
</li><li>
<p>Use escaped whitespace such as <code>\ </code>, i.e. a space preceded by a backslash.</p>
</li><li>
<p>Use a character class such as <code>[ ]</code>.</p>
</li></ul>
<p>Comments can be included in a non-<code>x</code> pattern with the <code>(?#</code><em>comment</em><code>)</code> construct, where <em>comment</em> is arbitrary text ignored by the regexp engine.</p>
<p>Comments in regexp literals cannot include unescaped terminator characters.</p>
<h2 id="label-Encoding"><a href="Encoding.html"><code>Encoding</code></a><span><a href="#label-Encoding">¶</a> <a href="#top">↑</a></span></h2>
<p>Regular expressions are assumed to use the source encoding. This can be overridden with one of the following modifiers.</p>
<ul><li>
<p><code>/</code><em>pat</em><code>/u</code> - UTF-8</p>
</li><li>
<p><code>/</code><em>pat</em><code>/e</code> - EUC-JP</p>
</li><li>
<p><code>/</code><em>pat</em><code>/s</code> - Windows-31J</p>
</li><li>
<p><code>/</code><em>pat</em><code>/n</code> - ASCII-8BIT</p>
</li></ul>
<p>A regexp can be matched against a string when they either share an encoding, or the regexp's encoding is <em>US-ASCII</em> and the string's encoding is ASCII-compatible.</p>
<p>If a match between incompatible encodings is attempted an <code>Encoding::CompatibilityError</code> exception is raised.</p>
<p>The <code>Regexp#fixed_encoding?</code> predicate indicates whether the regexp has a <em>fixed</em> encoding, that is one incompatible with ASCII. A regexp's encoding can be explicitly fixed by supplying <code>Regexp::FIXEDENCODING</code> as the second argument of <code>Regexp.new</code>:</p>
<pre class="ruby"><span class="ruby-identifier">r</span> = <span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">new</span>(<span class="ruby-string">"a"</span>.<span class="ruby-identifier">force_encoding</span>(<span class="ruby-string">"iso-8859-1"</span>),<span class="ruby-constant">Regexp</span><span class="ruby-operator">::</span><span class="ruby-constant">FIXEDENCODING</span>)
<span class="ruby-identifier">r</span> <span class="ruby-operator">=~</span> <span class="ruby-string">"a\u3042"</span>
<span class="ruby-comment"># raises Encoding::CompatibilityError: incompatible encoding regexp match</span>
<span class="ruby-comment"># (ISO-8859-1 regexp with UTF-8 string)</span>
</pre>
<h2 id="label-Special+global+variables">Special global variables<span><a href="#label-Special+global+variables">¶</a> <a href="#top">↑</a></span></h2>
<p>Pattern matching sets some global variables :</p>
<ul><li>
<p><code>$~</code> is equivalent to <a href="Regexp.html#method-c-last_match"><code>Regexp.last_match</code></a>;</p>
</li><li>
<p><code>$&</code> contains the complete matched text;</p>
</li><li>
<p><code>$`</code> contains string before match;</p>
</li><li>
<p><code>$'</code> contains string after match;</p>
</li><li>
<p><code>$1</code>, <code>$2</code> and so on contain text matching first, second, etc capture group;</p>
</li><li>
<p><code>$+</code> contains last capture group.</p>
</li></ul>
<p>Example:</p>
<pre class="ruby"><span class="ruby-identifier">m</span> = <span class="ruby-regexp">/s(\w{2}).*(c)/</span>.<span class="ruby-identifier">match</span>(<span class="ruby-string">'haystack'</span>) <span class="ruby-comment">#=> #<MatchData "stac" 1:"ta" 2:"c"></span>
<span class="ruby-identifier">$~</span> <span class="ruby-comment">#=> #<MatchData "stac" 1:"ta" 2:"c"></span>
<span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">last_match</span> <span class="ruby-comment">#=> #<MatchData "stac" 1:"ta" 2:"c"></span>
<span class="ruby-node">$&</span> <span class="ruby-comment">#=> "stac"</span>
<span class="ruby-comment"># same as m[0]</span>
<span class="ruby-node">$`</span> <span class="ruby-comment">#=> "hay"</span>
<span class="ruby-comment"># same as m.pre_match</span>
<span class="ruby-node">$'</span> <span class="ruby-comment">#=> "k"</span>
<span class="ruby-comment"># same as m.post_match</span>
<span class="ruby-node">$1</span> <span class="ruby-comment">#=> "ta"</span>
<span class="ruby-comment"># same as m[1]</span>
<span class="ruby-node">$2</span> <span class="ruby-comment">#=> "c"</span>
<span class="ruby-comment"># same as m[2]</span>
<span class="ruby-node">$3</span> <span class="ruby-comment">#=> nil</span>
<span class="ruby-comment"># no third group in pattern</span>
<span class="ruby-node">$+</span> <span class="ruby-comment">#=> "c"</span>
<span class="ruby-comment"># same as m[-1]</span>
</pre>
<p>These global variables are thread-local and method-local variables.</p>
<h2 id="label-Performance">Performance<span><a href="#label-Performance">¶</a> <a href="#top">↑</a></span></h2>
<p>Certain pathological combinations of constructs can lead to abysmally bad performance.</p>
<p>Consider a string of 25 <em>a</em>s, a <em>d</em>, 4 <em>a</em>s, and a <em>c</em>.</p>
<pre class="ruby"><span class="ruby-identifier">s</span> = <span class="ruby-string">'a'</span> <span class="ruby-operator">*</span> <span class="ruby-value">25</span> <span class="ruby-operator">+</span> <span class="ruby-string">'d'</span> <span class="ruby-operator">+</span> <span class="ruby-string">'a'</span> <span class="ruby-operator">*</span> <span class="ruby-value">4</span> <span class="ruby-operator">+</span> <span class="ruby-string">'c'</span>
<span class="ruby-comment">#=> "aaaaaaaaaaaaaaaaaaaaaaaaadaaaac"</span>
</pre>
<p>The following patterns match instantly as you would expect:</p>
<pre class="ruby"><span class="ruby-regexp">/(b|a)/</span> <span class="ruby-operator">=~</span> <span class="ruby-identifier">s</span> <span class="ruby-comment">#=> 0</span>
<span class="ruby-regexp">/(b|a+)/</span> <span class="ruby-operator">=~</span> <span class="ruby-identifier">s</span> <span class="ruby-comment">#=> 0</span>
<span class="ruby-regexp">/(b|a+)*/</span> <span class="ruby-operator">=~</span> <span class="ruby-identifier">s</span> <span class="ruby-comment">#=> 0</span>
</pre>
<p>However, the following pattern takes appreciably longer:</p>
<pre class="ruby"><span class="ruby-regexp">/(b|a+)*c/</span> <span class="ruby-operator">=~</span> <span class="ruby-identifier">s</span> <span class="ruby-comment">#=> 26</span>
</pre>
<p>This happens because an atom in the regexp is quantified by both an immediate <code>+</code> and an enclosing <code>*</code> with nothing to differentiate which is in control of any particular character. The nondeterminism that results produces super-linear performance. (Consult <em>Mastering Regular Expressions</em> (3rd ed.), pp 222, by <em>Jeffery Friedl</em>, for an in-depth analysis). This particular case can be fixed by use of atomic grouping, which prevents the unnecessary backtracking:</p>
<pre class="ruby">(<span class="ruby-identifier">start</span> = <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span>) <span class="ruby-operator">&&</span> <span class="ruby-regexp">/(b|a+)*c/</span> <span class="ruby-operator">=~</span> <span class="ruby-identifier">s</span> <span class="ruby-operator">&&</span> (<span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span> <span class="ruby-operator">-</span> <span class="ruby-identifier">start</span>)
<span class="ruby-comment">#=> 24.702736882</span>
(<span class="ruby-identifier">start</span> = <span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span>) <span class="ruby-operator">&&</span> <span class="ruby-regexp">/(?>b|a+)*c/</span> <span class="ruby-operator">=~</span> <span class="ruby-identifier">s</span> <span class="ruby-operator">&&</span> (<span class="ruby-constant">Time</span>.<span class="ruby-identifier">now</span> <span class="ruby-operator">-</span> <span class="ruby-identifier">start</span>)
<span class="ruby-comment">#=> 0.000166571</span>
</pre>
<p>A similar case is typified by the following example, which takes approximately 60 seconds to execute for me:</p>
<p>Match a string of 29 <em>a</em>s against a pattern of 29 optional <em>a</em>s followed by 29 mandatory <em>a</em>s:</p>
<pre class="ruby"><span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">new</span>(<span class="ruby-string">'a?'</span> <span class="ruby-operator">*</span> <span class="ruby-value">29</span> <span class="ruby-operator">+</span> <span class="ruby-string">'a'</span> <span class="ruby-operator">*</span> <span class="ruby-value">29</span>) <span class="ruby-operator">=~</span> <span class="ruby-string">'a'</span> <span class="ruby-operator">*</span> <span class="ruby-value">29</span>
</pre>
<p>The 29 optional <em>a</em>s match the string, but this prevents the 29 mandatory <em>a</em>s 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.</p>
<p>The best way to improve performance is to significantly reduce the amount of backtracking needed. For this case, instead of individually matching 29 optional <em>a</em>s, a range of optional <em>a</em>s can be matched all at once with <em>a{0,29}</em>:</p>
<pre class="ruby"><span class="ruby-constant">Regexp</span>.<span class="ruby-identifier">new</span>(<span class="ruby-string">'a{0,29}'</span> <span class="ruby-operator">+</span> <span class="ruby-string">'a'</span> <span class="ruby-operator">*</span> <span class="ruby-value">29</span>) <span class="ruby-operator">=~</span> <span class="ruby-string">'a'</span> <span class="ruby-operator">*</span> <span class="ruby-value">29</span>
</pre>
</main>
<footer id="validator-badges" role="contentinfo">
<p><a href="https://validator.w3.org/check/referer">Validate</a>
<p>Generated by <a href="https://ruby.github.io/rdoc/">RDoc</a> 6.2.1.1.
<p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>.
</footer>