0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
h-kach
  • 351
  • 2
  • 8
  • 25
  • Yep, that is right. #keyword is basically a keyword. Will edit the question to remove the confusion – h-kach Mar 07 '16 at 12:47
  • yes, spaces can occur before or after the #comment. Also note that #keyword is a set of keywords I am using. for eg, it can be #comment, #transition and etc. so using #[a-zA-Z] doesn't suffice. I need to match the exact word #comment or #transition, hope its clear – h-kach Mar 07 '16 at 12:52
  • I edited the question to remove any confusion. I need to match zero or one occurrence of #comment. Space can occur below and after #comment. – h-kach Mar 07 '16 at 12:54

2 Answers2

1

#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]*)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
achabahe
  • 2,445
  • 1
  • 12
  • 21
  • I edited the question. There was a confusion earlier – h-kach Mar 07 '16 at 12:55
  • ok ihave chahged the regex try it it should work i have tried on TXT-234 #coMMENt anychars and matched – achabahe Mar 07 '16 at 13:01
  • Yes, that was silly from my end, had included space outside the match whereas it should've been inside the group with #comment. Thanks! – h-kach Mar 07 '16 at 16:53
0

This may help;

String str = "1. TXT-234 #comment anychars";
String str2 = "2. TXT-234 anychars";
String str3 = "3. TXT-2a34 anychars";
String str4 = "4. TXT.234 anychars";
Pattern pattern = Pattern.compile("([a-zA-Z]*-\\d*\\s(#[a-zA-Z]+\\s)?[a-zA-Z]*)");
Matcher m = pattern.matcher(str);
if (m.find()) {
    System.out.println("Found value: " + m.group(0));
    System.out.println("Found value: " + m.group(1));
    System.out.println("Found value: " + m.group(2));
}
m = pattern.matcher(str2);
if (m.find()) {
    System.out.println("Found value: " + m.group(0));
}
m = pattern.matcher(str3);
if (m.find()) {
    System.out.println("Found value: " + m.group(0));
} else {
    System.out.println("str3 not match");
}
m = pattern.matcher(str4);
if (m.find()) {
    System.out.println("Found value: " + m.group(0));
} else {
    System.out.println("str4 not match");
}
Yusuf K.
  • 4,195
  • 1
  • 33
  • 69