簡體   English   中英

在 Java 中匹配零或一次出現的單詞的正則表達式

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

我寫了一個正則表達式來匹配以下模式:

任何字符,后跟hyphen后跟number后跟space后跟可選的case insensitive keyword后跟space后跟任何char

例如,

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

我寫的正則表達式如下:

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

但是上面沒有捕獲 '#comment' 的零出現,即使我已經指定了 '?' 對於正則表達式。 上例中的案例 2 總是失敗,案例 1 成功。

我究竟做錯了什么?

#comment 與 #keyword 不匹配。 這就是為什么您沒有匹配嘗試的原因。 這個它應該工作:

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

這可能會有所幫助;

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