× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Extract Value from String using Regular Expressions in Ruby

Leif Gensert
Apr 01, 2016
<p>There are a million ways to extract values from a string in Ruby. The easiest way that I found and that I constantly use is the [] operator together with <a href="http://www.rexegg.com/regex-capture.html">capture groups</a>.</p> <p>Take for example the string: "Name: Leif"</p> <p>If you want to capture the name (defined as: all letters appearing right of "Name: ") you do this:</p> <pre><code class="language-ruby">"Name: Leif"[/Name: (\w+)/, 1] # =&gt; Leif</code></pre> <p>The first parameter defines the regular expression and the capture group that you want to use, the second parameter defines the group number you want to find (0 the whole string, 1 the first, 2 the second..)</p> <p> </p> <p>If you use named groups you can also reference them by a symbol or string:</p> <pre><code class="language-ruby">"Name: Leif Gensert"[/Name: (?&lt;first_name&gt;\w+) (?&lt;last_name&gt;\w+)/, :first_name] # =&gt; Leif</code></pre>
comments powered by Disqus