2014-10-09 69 views
0

我需要用於驗證進來圖案像NBTAAA-PREM_001NBTAAA_001正則表達式進行字符串驗證

NBTAAA部分可以是數字或字母或字母數字,任選接着進行固定字符串-PREM(連字符PREM)將字符串一個正則表達式,然後強調_,後跟三個字母數字字符。

對於這個「NBTAAA_001」,需要不帶'-PREM'的正則表達式(連字符PREM)。

我寫的代碼:

public static void main(String[] args) { 
    List<String> input = new ArrayList<String>(); 

    input.add("NBTAAA-PRIM_001"); 
    input.add("NBTAAA_001"); 

    for (String ssn : input) { 
     // String ssn = "NBTAAA-PRIM_001"; 
     if (ssn.indexOf("-") != -1) { 
      int PRIMbeginIndex = ssn.indexOf("-") + 1; 
      int PRIMEndIndex = PRIMbeginIndex + 4; 

      String d = ssn.substring(PRIMbeginIndex, PRIMEndIndex); 

      if (d.equalsIgnoreCase("PRIM")) { 

       if (ssn.matches("^([A-Za-z0-9]+(?=.*?\bPRIM\b)+_[A-Za-z0-9]{3})$")) { 
        System.out.println(" PRIM image value : " + ssn); 
       } 
      } 
     } 
     else { 
      if (ssn.matches("^([A-Za-z0-9]+_[A-Za-z0-9]{3})$")) { 
       System.out.println("NORMAL IMAGE value : " + ssn); 
      } 
     } 
    } 
} 

但它不能正常工作。請幫我解決這個問題。

+2

它是PRIM還是PREM? – nhahtdh 2014-10-09 05:39:01

+0

只有PREM。 – 2014-10-09 07:17:34

+0

您是否希望PREM'部分不區分大小寫? – nhahtdh 2014-10-09 07:19:21

回答

0
^[a-zA-Z0-9]+(?:-PREM)?_[a-zA-Z0-9]{3}$ 

你可以試試看。

http://regex101.com/r/iM2wF9/16

+0

爲什麼downvoted ????????????????? – vks 2014-10-09 05:53:11

+0

感謝您的回答。它工作正常 – 2014-10-09 07:13:42

+0

@ user2945308歡迎您。 – vks 2014-10-09 07:14:08