[Solved] Find the highest number between two literal strings using a Regular Expression


You can use this code to extract the numeric portion from the untitledNNN.java file name:

Pattern p = Pattern.compile("^untitled(\\d+)[.]java$", Pattern.CASE_INSENSITIVE);
for (String fileName : fileNames) {
    Matcher m = p.matcher(fileName);
    if (!m.find()) {
        continue;
    }
    String digits = m.group(1);
    ... // Parse and find the max
}

Demo.

Since you are OK with throwing an exception when the number does not fit in an int, you could mark your method with throws NumberFormatException, and use Integer.parseInt(digits) to get the value. After that you could compare the number with maxSuffix, a running max value of the sequence. You should start maxSuffix at zero, not at one, because you will increment it at the end.

To avoid an overflow, check if maxSuffix is equal to Integer.MAX_VALUE before returning maxSuffix+1.

3

solved Find the highest number between two literal strings using a Regular Expression