简体   繁体   English

在 Java 中匹配零或一次出现的单词的正则表达式

[英]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 .任何字符,后跟hyphen后跟number后跟space后跟可选的case insensitive keyword后跟space后跟任何char

Eg,例如,

  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 '?'但是上面没有捕获 '#comment' 的零出现,即使我已经指定了 '?' for the regular expression.对于正则表达式。 The case 2 in the above example always fails and the case 1 succeeds.上例中的案例 2 总是失败,案例 1 成功。

What am I doing wrong?我究竟做错了什么?

#comment won't match #keyword. #comment 与 #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]*)

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM