2015-02-09 70 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,并给他们一个组