Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>'[ruby] regex'.scan(/\[(.*?)\](.*)/) </code></pre> <p>will return</p> <pre><code>[["ruby", " regex"]] </code></pre> <p>you can read more about String#scan here: <a href="http://ruby-doc.org/core/classes/String.html#M000812" rel="noreferrer">http://ruby-doc.org/core/classes/String.html#M000812</a> (in short it returns an array of all consecutive matches, the outer array in this case is the array of matches, and the inner is the capture groups of the one match).</p> <p>to do the assignment you can rewrite it like this (assuming you will only ever have one match in the string):</p> <pre><code>tag, keyword = '[ruby] regex'.scan(/\[(.*?)\](.*)/).flatten </code></pre> <p>depending on exactly what you want to accomplish you may want to change the regex to </p> <pre><code>/^\s*\[(.*?)\]\s*(.+)\s*$/ </code></pre> <p>which matches the whole input string, and trims some spaces from the second capture group. Anchoring the pattern to the start and end will make it a bit more efficient, and it will avoid getting false or duplicate matches in some cases (but that very much depends on the input) -- it also guarantees that you can safely use the returned array in assignment, because it will never have more than one match.</p> <p>As for the follow up question, this is what I would do:</p> <pre><code>def tags_and_keyword(input) input.scan(/^\s*\[(.+)\]\s+(.+)\s*$/) do |match| tags = match[0].split(/\]\s*\[/) line = match[1] return tags, line end end tags, keyword = tags_and_keyword('[ruby] [regex] [rails] one line') tags # =&gt; ["ruby", "regex", "rails"] keyword # =&gt; "one line" </code></pre> <p>it can be rewritten in one line, but I wouldn't:</p> <pre><code>tags, keyword = catch(:match) { input.scan(/^\s*\[(.+)\]\s+(.+)\s*$/) { |match| throw :match, [match[0].split(/\]\s*\[/), match[1]] } } </code></pre> <p>My solution assumes all tags come before the keyword, and that there's only one tags/keyword expression in each input. The first capture globs all tags, but then I split that string, so it's a two-step process (which, as @Tim wrote in his comment, is required unless you have an engine capable of recursive matching).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload