gpt4 book ai didi

java - dicom 年龄的正则表达式

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:36 25 4
gpt4 key购买 nike

我正在尝试创建正则表达式。有一个年龄,可以用多种方式写成:

例如对于 64 岁的人来说,它可能是:

  • 064Y
  • 064
  • 64

但是对于0岁也可以

  • 0是
  • 0

你能帮我为 JAVA 匹配器生成正确的正则,这样我就可以在解析这个年龄字符串后得到 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);

}

非常感谢您的帮助,谢谢。

最佳答案

我会尝试使用以下自包含示例:

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

关于java - dicom 年龄的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28414681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com