DAVE
DAVE

Reputation: 61

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.

Upvotes: 1

Views: 195

Answers (2)

Hülya
Hülya

Reputation: 3433

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

Upvotes: 3

sanjeevRm
sanjeevRm

Reputation: 1606

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;

    }
}

Upvotes: 2

Related Questions