A regular expression to match zero or one occurrence of a word in Java
<p>I have written a regex to match following pattern:</p>
<p>Any characters followed by <code>hyphen</code> followed by <code>number</code> followed by <code>space</code> followed by an optional <code>case insensitive keyword</code> followed by <code>space</code> followed by any <code>char</code>.</p>
<p>E.g.,</p>
<blockquote>
<ol>
<li><code>TXT-234 #comment anychars</code></li>
<li><code>TXT-234 anychars</code></li>
</ol>
</blockquote>
<p>The regular expression I have written is as follows:</p>
<pre><code>(?&lt;issueKey&gt;^((\\s*[a-zA-Z]+-\\d+)\\s+)+)((?i)?&lt;keyWord&gt;#comment)?\\s+(?&lt;comment&gt;.*)
</code></pre>
<p>But the above doesn't capture the zero occurrence of '#comment', even though I have specified the '?' for the regular expression. The case 2 in the above example always fails and the case 1 succeeds.</p>
<p>What am I doing wrong?</p>