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

What is the best way to use regex to get the highest number in a group of strings that match a certain pattern.
For example:

Suppose I wanted to find the next integer to suffix an Untitled file.

Here is an an example of already existing file names:

  • Untitled1.java -> should match
  • untitled2.java -> should match (case insensitive)
  • MyFile.java -> should not match (does not contain Untitled#.java)
  • NotUntitled3.java -> should not match (does not exactly match Untitled#.java)

In this example the function below should return: 3

    public int getNextUntitledFileSuffix(String[] fileNames){
      int nextSuffix = 1;
      int maxSuffix = 1;
      for (int i = 0; i < fileNames.length; i++){
        //use regex to set nextSuffix
      }
      return nextSuffix;
    }


Source: regex

Leave a Reply