Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need the <code>Regexp#match</code> method. If you write <code>/\[(.*?)\](.*)/.match('[ruby] regex')</code>, this will return a <code>MatchData</code> object. If we call that object <code>matches</code>, then, among other things:</p> <ul> <li><code>matches[0]</code> returns the whole matched string.</li> <li><code>matches[n]</code> returns the nth capturing group (<code>$n</code>).</li> <li><code>matches.to_a</code> returns an array consisting of <code>matches[0]</code> through <code>matches[N]</code>.</li> <li><code>matches.captures</code> returns an array consisting of just the capturing group (<code>matches[1]</code> through <code>matches[N]</code>).</li> <li><code>matches.pre_match</code> returns everything before the matched string.</li> <li><code>matches.post_match</code> returns everything after the matched string.</li> </ul> <p>There are more methods, which correspond to other special variables, etc.; you can check <a href="http://ruby-doc.org/core/classes/MatchData.html" rel="nofollow noreferrer"><code>MatchData</code>'s docs</a> for more. Thus, in this specific case, all you need to write is</p> <pre><code>tag, keyword = /\[(.*?)\](.*)/.match('[ruby] regex').captures </code></pre> <hr> <p><strong>Edit 1:</strong> Alright, for your harder task, you're going to instead want the <code>String#scan</code> method, which <a href="https://stackoverflow.com/questions/3090786/how-to-use-one-line-regular-expression-to-get-matched-content/3090808#3090808">@Theo</a> used; however, we're going to use a different regex. The following code should work:</p> <pre><code># You could inline the regex, but comments would probably be nice. tag_and_text = / \[([^\]]*)\] # Match a bracket-delimited tag, \s* # ignore spaces, ([^\[]*) /x # and match non-tag search text. input = '[ruby] [regex] [rails] one line [foo] [bar] baz' tags, texts = input.scan(tag_and_text).transpose </code></pre> <p>The <code>input.scan(tag_and_text)</code> will return a list of tag–search-text pairs:</p> <pre><code>[ ["ruby", ""], ["regex", ""], ["rails", "one line "] , ["foo", ""], ["bar", "baz"] ] </code></pre> <p>The <code>transpose</code> call flips that, so that you have a pair consisting of a tag list and a search-text list:</p> <pre><code>[["ruby", "regex", "rails", "foo", "bar"], ["", "", "one line ", "", "baz"]] </code></pre> <p>You can then do whatever you want with the results. I might suggest, for instance</p> <pre><code>search_str = texts.join(' ').strip.gsub(/\s+/, ' ') </code></pre> <p>This will concatenate the search snippets with single spaces, get rid of leading and trailing whitespace, and replace runs of multiple spaces with a single space.</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