Search code examples
javaregexcapturing-group

A regular expression to match zero or one occurrence of a word in Java


I have written a regex to match following pattern:

Any characters followed by hyphen followed by number followed by space followed by an optional case insensitive keyword followed by space followed by any char.

E.g.,

  1. TXT-234 #comment anychars
  2. TXT-234 anychars

The regular expression I have written is as follows:

(?<issueKey>^((\\s*[a-zA-Z]+-\\d+)\\s+)+)((?i)?<keyWord>#comment)?\\s+(?<comment>.*)

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.

What am I doing wrong?


Solution

  • #comment won't match #keyword. That is why you don't have a match try. This one it should work:

     ([a-zA-Z]*-\\d*\\s(((?i)#comment|#transition|#keyword)+\\s)?[a-zA-Z]*)