我會嘗試用下面的自足例如:
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
中還能有多個'0s'之前,第一個數字? 00064Y'有效嗎? – 2015-02-09 16:39:26
任何提示答案的人都應確保前導零不包含在匹配中,因爲具有前導零的數字將被解析爲八進制數。 – mbomb007 2015-02-09 16:47:37