title: regex optional word
body: <p>I am trying to find a regex that will match each of the following cases from a set of <code>ldap objectclass</code> definitions - they're just strings really.  </p>
  
  <p>The variations in the syntax are tripping my regex up and I don't seem to be able to find a balance between the greedy nature of the match and the optional word "MAY".  </p>
  
  <pre><code>( class1-OID NAME 'class1' SUP top STRUCTURAL MUST description MAY ( brand $ details $ role ) )
  </code></pre>
  
  <p>DESIRED OUTPUT: description <br>
  ACTUAL GROUP1: description <br>
  ACTUAL GROUP1 with ? on the MAY group: description MAY<br></p>
  
  <pre><code>( class2-OID NAME 'class2' SUP top STRUCTURAL MUST groupname MAY description )
  </code></pre>
  
  <p>DESIRED OUTPUT: groupname<br> 
  ACTUAL GROUP1: groupname <br>
  ACTUAL GROUP1 with ? on the MAY group: groupname MAY description<br></p>
  
  <pre><code>( class3-OID NAME 'class3' SUP top STRUCTURAL MUST ( code $ name ) )
  </code></pre>
  
  <p>DESIRED OUTPUT: code $ name<br>
  ACTUAL GROUP1: <strong>no match</strong><br>
  ACTUAL GROUP1 with ? on the MAY group: code $ name<br></p>
  
  <pre><code>( class4-OID NAME 'class4' SUP top STRUCTURAL MUST ( code $ name ) MAY ( group $ description ) )
  </code></pre>
  
  <p>DESIRED OUTPUT: code $ name<br>
  ACTUAL GROUP1: code $ name<br>
  ACTUAL GROUP1 with ? on the MAY group: code $ name<br></p>
  
  <p>Using this:</p>
  
  <p><code>MUST \(?([\w\$\-\s]+)\)?\s*(?:MAY)</code> (<a href="https://regex101.com/r/nrBjqR/1" rel="nofollow noreferrer">Regex101</a>)</p>
  
  <p>matches lines 1, 2 and 4, but doesn't match the 3rd one with no <code>MAY</code> statement.
  Adding an optional "?" to the <code>MAY</code> group results in a good match for 3 and 4, but then the 1st and 2nd lines act greedily and run on into <code>MAY</code> (line 1) or the remainder of the string (line 2).</p>
  
  <p>It feels like I need the regex to consider <code>MAY</code> as optional but also that if <code>MAY</code> is found it should stop - I don't seem to be able to find that balance.</p>