javaregexcharindexoflastindexof

Trying to find the index of the last uppercase char using regex


I need a little bit of help trying to find the last index of the last uppercase char in the string. I have been using regex to do so. However it keeps returning -1 instead of the index of B which is 7.

The code is highlighted below

public class Main {
    public static void main(String[] args) {
        String  s2 = "A3S4AA3B3";
        int lastElementIndex = s2.lastIndexOf("[A-Z]");
        System.out.println(lastElementIndex);
    }
}

Does anyone have any recommendation on how to fix the issue?

Kind regards.


Solution

  • You can try the regex [A-Z][^A-Z]*$ :

    String  s2 = "A3S4AA3B3";
    Matcher m = Pattern.compile("[A-Z][^A-Z]*$").matcher(s2);
    if(m.find()) {
        System.out.println("last index: " + m.start());
    }
    

    Output:

    last index: 7
    

    About the regex: