Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You want to use <code>scan</code> for this sort of thing. The basic pattern would be this:</p> <pre><code>s.scan(/\w+/) </code></pre> <p>That would give you an array of all the contiguous sequences for word characters:</p> <pre><code>&gt;&gt; "@Identifier('VariableA', 'VariableB', 'VariableX', 'VariableZ')".scan(/\w+/) =&gt; ["Identifier", "VariableA", "VariableB", "VariableX", "VariableZ"] </code></pre> <p>You say you might have multiple instances of your pattern with arbitrary stuff surrounding them. You can deal with that with nested <code>scan</code>s:</p> <pre><code>s.scan(/@(\w+)\(([^)]+?)\)/).map { |m| [ m.first, m.last.scan(/\w+/) ] } </code></pre> <p>That will give you an array of arrays, each inner array will have the "Identifier" part as the first element and that "Variable" parts as an array in the second element. For example:</p> <pre><code>&gt;&gt; s = "pancakes @Identifier('VariableA', 'VariableB', 'VariableX', 'VariableZ') pancakes @Pancakes('one','two','three') eggs" &gt;&gt; s.scan(/@(\w+)\(([^)]+?)\)/).map { |m| [ m.first, m.last.scan(/\w+/) ] } =&gt; [["Identifier", ["VariableA", "VariableB", "VariableX", "VariableZ"]], ["Pancakes", ["one", "two", "three"]]] </code></pre> <p>If you might be facing escaped quotes inside your "Variable" bits then you'll need something more complex.</p> <hr> <p>Some notes on the expression:</p> <pre><code>@ # A literal "@". ( # Open a group \w+ # One more more ("+") word characters ("\w"). ) # Close the group. \( # A literal "(", parentheses are used for group so we escape it. ( # Open a group. [ # Open a character class. ^) # The "^" at the beginning of a [] means "not", the ")" isn't escaped because it doesn't have any special meaning inside a character class. ] # Close a character class. +? # One more of the preceding pattern but don't be greedy. ) # Close the group. \) # A literal ")". </code></pre> <p>You don't really need <code>[^)]+?</code> here, just <code>[^)]+</code> would do but I use the non-greedy forms by habit because that's usually what I mean. The grouping is used to separate the <code>@Identifier</code> and <code>Variable</code> parts so that we can easily get the desired nested array output.</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