1

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.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
DAVE
  • 61
  • 4
  • `String#lastIndexOf` accepts a string and not a regex. – Eritrean Apr 10 '21 at 14:34
  • That comment is relevant, but does not answer the OP's question, which I would rewrite as "is there an equivalent to `lastIndexOf` that accepts a regular expression?" – joanis Apr 10 '21 at 14:39

2 Answers2

3

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:

  • [A-Z] : uppercase letter
  • [^A-Z]* : ^ means negation, may contain other chars * zero or more times
  • $ : end of line
Hülya
  • 3,353
  • 2
  • 12
  • 19
2

You can get index of last uppercase letter as below

int count = 0;
int lastIndex = -1;
for (char c : s2.toCharArray()) {
       count++;  
    if (Character.isUpperCase(c)) {
       lastIndex = count;

    }
}

sanjeevRm
  • 1,541
  • 2
  • 13
  • 24