2011-10-16 46 views
0

我有一個字符串部分與以下模式匹配。

ABCD |(| A | AB | ABC)E(FGHI |(| F | FG | FGH)jklmn)

但問題我有是,我的整個字符串被重複的組合像上面這樣的模式。而我的整個字符串必須包含超過14套以上的模式。
任何人都可以幫助我將上述RegEx改進爲想要的格式。

由於

更新
輸入例子:
匹配的字符串部分:ABCD,abefgjkln,efjkln,ejkln
但是整個字符串是:abcdabefgjklnefjklnejkln(上面4份的組合)

必須有整串超過15個零件。以上只有4個部分。所以,這是錯誤的。正則表達式中的重複模式

+2

ABCD |(|一個你知道你是這裏沒有任何匹配,並在其他地方還有你的正則表達式可以改寫爲更簡單更簡潔的正則表達式請提供輸入和輸出?。 – FailedDev

+0

@FailedDev我已經添加了一個例子,我是RegEx的初學者,所以我的RegEx中一定有問題,如果你也可以幫忙,那就太好了,謝謝。 – SachiraChin

+0

這些是唯一的部分你想匹配嗎?(abcd,abefgjkln,efjkln,ejkln) – FailedDev

回答

5

這將嘗試在字符串中至少匹配您的「部分」至少15次。

boolean foundMatch = false; 
    try { 
     foundMatch = subjectString.matches("(?:(?:ab(?:cd|efgjkln))|(?:(?:ef?jkln))){15,}"); 
    } catch (PatternSyntaxException ex) { 
     // Syntax error in the regular expression 
    } 

如果上述任何部分至少有15次重複,那麼foundMatch將爲true,否則它將保持爲假。

擊穿:

"(?:" +      // Match the regular expression below 
    "|" +       // Match either the regular expression below (attempting the next alternative only if this one fails) 
     "(?:" +      // Match the regular expression below 
     "ab" +      // Match the characters 「ab」 literally 
     "(?:" +      // Match the regular expression below 
              // Match either the regular expression below (attempting the next alternative only if this one fails) 
       "cd" +      // Match the characters 「cd」 literally 
      "|" +       // Or match regular expression number 2 below (the entire group fails if this one fails to match) 
       "efgjkln" +     // Match the characters 「efgjkln」 literally 
     ")" + 
     ")" + 
    "|" +       // Or match regular expression number 2 below (the entire group fails if this one fails to match) 
     "(?:" +      // Match the regular expression below 
     "(?:" +      // Match the regular expression below 
      "e" +       // Match the character 「e」 literally 
      "f" +       // Match the character 「f」 literally 
       "?" +       // Between zero and one times, as many times as possible, giving back as needed (greedy) 
      "jkln" +      // Match the characters 「jkln」 literally 
     ")" + 
     ")" + 
"){15,}"      // Between 15 and unlimited times, as many times as possible, giving back as needed (greedy) 
+0

感謝您的幫助。 :)這正是我想要的。謝謝。 – SachiraChin

-1

首先,你的模式似乎可以簡化。真正圖案aab的子集,它是abc的子集,因此如果圖案abc匹配,則意味着a也匹配。想想這個,並適當地改變你的模式。現在它可能不是你真正想要的。

其次,重複一些事情是推遲使用{N},即abc{5}意味着「abc重複五次」。您也可以使用{3,},{,5},{3,5}表示重複> = 3,重複< = 5,3 < =重複< = 5。

+0

abc {5}表示「abc重複五次」不,它不。abc {5}表示ab接着5次c。(?:abc){5} m回答你說的話。 – FailedDev

+0

我仍然不明白我在RegEx中如何使用它。您可以用我的RegEx將它展示給我嗎?謝謝。 – SachiraChin

1

這個怎麼樣:

(?:a(?:b(?:c(?:d)?)?)?ef(?:g(?:h(?:i)?)?)?jklmn){15,} 

說明:您創建一個非捕獲組((?: ...)),並說,這應該被重複> = 15倍,因此在最後的大括號。