2015-02-09 98 views
3

我正在嘗試創建正則表達式。 有一個年齡,可以用多種方式寫:dicom時間的正則表達式

例如,對人64歲則可能是:

  • 064Y

但對於0歲也有可能是

  • 0Y

你能幫我爲JAVA matcher生產正確的,所以我可以在解析這個年齡字符串後得到Integer。

目前我來到以下,這顯然不包括所有可能的情況。

@Test 
    public void testAgeConverter() throws AppException, IOException { 
    Pattern pattern = Pattern.compile("0([0-9]+|[1-9]+)[Yy]?"); 

    Matcher m = pattern.matcher("062Y"); 
    String str = ""; 
    if (m.find()) { 
     for (int i = 1; i <= m.groupCount(); i++) { 
     str += "\n" + m.group(i); 
     } 
    } 

    System.out.println(str); 

    } 

我會感謝您的幫助,謝謝。

+1

中還能有多個'0s'之前,第一個數字? 00064Y'有效嗎? – 2015-02-09 16:39:26

+0

任何提示答案的人都應確保前導零不包含在匹配中,因爲具有前導零的數字將被解析爲八進制數。 – mbomb007 2015-02-09 16:47:37

回答

2

我會嘗試用下面的自足例如:

String[] testCases = { 
     "064Y", "064", "64", "0Y", "0" 
}; 
int[] expectedResults = { 
     64, 64, 64, 0, 0 
}; 
//       ┌ optional leading 0 
//       | ┌ 1 or 2 digits from 0 to 9 (00->99) 
//       | | in group 1 
//       | |   ┌ optional one Y 
//       | |   | ┌ case insensitive 
Pattern p = Pattern.compile("0*([0-9]{1,2})Y?", Pattern.CASE_INSENSITIVE); 
// fine-tune the Pattern for centenarians 
// (up to 199 years in this ugly draft): 
// "0*([0-1][0-9]{1,2}"; 
for (int i = 0; i < testCases.length; i++) { 
    Matcher m = p.matcher(testCases[i]); 
    if (m.find()) { 
     System.out.printf("Found: %s%n", m.group()); 
     int result = Integer.parseInt(m.group(1)); 
     System.out.printf("Expected result is: %d, actual result is: %d", expectedResults[i], result); 
     System.out.printf("... matched? %b%n", result == expectedResults[i]); 
    } 
} 

輸出

Found: 064Y 
Expected result is: 64, actual result is: 64... matched? true 
Found: 064 
Expected result is: 64, actual result is: 64... matched? true 
Found: 64 
Expected result is: 64, actual result is: 64... matched? true 
Found: 0Y 
Expected result is: 0, actual result is: 0... matched? true 
Found: 0 
Expected result is: 0, actual result is: 0... matched? true 
+0

不錯,但是使用'[0-9] {1,3}',百歲老人並不罕見(或者[[0-9] +'可以讓將來的醫療進步:)。 – 2015-02-09 16:45:35

+0

@TimPietzcker好點。讓我們來看看這裏的一些希望吧:D – Mena 2015-02-09 16:46:41

+0

@TimPietzcker,雖然經過深思熟慮,但還不確定標準是什麼。 100年? 110? – Mena 2015-02-09 16:48:56

0

在任何情況下,你只需要數字,所以你可以使用

[0]*((\d)*) 

注意,使它在Java工作,你必須逃離backslash所以

[0]*((\\d)*) 

然後,只需捕捉第一個匹配組。

這將選擇除前導零之外的所有數字。在00Y的情況下,將選擇什麼,但那麼你可以用

if(result.isEmpty()) 
    val = 0; 
0

輕鬆地檢查你可以嘗試使用類似這樣:^0*?(\d+)Y?$。一個工作示例可用here。然後,您將迭代匹配並使用正則表達式組來提取您之後的整數值。

0

爲什麼你的表情如此複雜?這不會...嗎?

Pattern pattern = Pattern.compile("([0-9]+)[Yy]?"); 

    Matcher m = pattern.matcher("062Y"); 
    Integer age = null; 
    if (m.find()) { 
     age = Integer.valueOf(m.group(1)); 
    } 

    System.out.println(age); 
0

您需要更具體的用正則表達式也可以是問題解決與:

[0-9]+[Y|y]? 

但是,這不會幫助你多少,你應該試着和周圍的這些值

0

唯一標識符更縮小它如果您正在使用matcher.find,它甚至沒有必要匹配前導零;既不匹配[yY],因此,我們有:

(1[0-9][0-9]|[1-9]?[0-9]) 

它會發現所有從0整數199,並給他們一個組