【问题标题】:Trying to find the index of the last uppercase char using regex尝试使用正则表达式查找最后一个大写字符的索引
【发布时间】:2021-04-10 14:31:14
【问题描述】:

我需要一些帮助来尝试查找字符串中最后一个大写字符的最后一个索引。我一直在使用正则表达式来做到这一点。但是它一直返回 -1 而不是 B 的索引 7。

代码在下方突出显示

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

有人对如何解决这个问题有任何建议吗?

亲切的问候。

【问题讨论】:

  • String#lastIndexOf 接受字符串而不是正则表达式。
  • 该评论是相关的,但没有回答 OP 的问题,我将其重写为“是否有等效于 lastIndexOf 的接受正则表达式?”

标签: java regex char indexof lastindexof


【解决方案1】:

你可以试试正则表达式[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());
}

输出:

last index: 7

关于正则表达式:

  • [A-Z] : 大写字母
  • [^A-Z]* : ^ 表示否定,可能包含其他字符 * 零次或多次
  • $ : 行尾

【讨论】:

    【解决方案2】:

    你可以得到最后一个大写字母的索引,如下所示

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

    【讨论】:

    • 从头开始减少迭代次数。
    • 谢谢你的朋友,就是这样
    • sanjeevRm 我如何只获得最后一次迭代
    • 如建议的那样,要获得最后一次迭代,如果您以相反的顺序迭代数组,则 from last index 第一个匹配的字母将是您的元素
    猜你喜欢
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多