gpt4 book ai didi

java - 查找 Java 字符串中给定字符之前的最后一个字符

转载 作者:行者123 更新时间:2023-12-01 17:10:00 26 4
gpt4 key购买 nike

假设我有以下字符串:

String string = "122045b5423";

在 Java 中,查找 b 之前的最后 2 个最有效的方法是什么?我知道我可以拆分字符串,然后使用 String 类中的 lastIndexOf() 方法,但是有没有一种更有效的方法来减少变量的创建。 StringBuilder 类中是否有一个方法可以让我们做到这一点?

最佳答案

如果您正在寻找更紧凑的解决方案,那么正则表达式怎么样?

// A 2, followed by arbitrary chars that are not a 2 and finally a b
Pattern pattern = Pattern.compile("(2)[^2]*b");
Matcher matcher = pattern.matcher(string);

if (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end());
System.out.println(" Found: " + matcher.group());
}

还没有测试过,但类似的东西应该可以工作

关于java - 查找 Java 字符串中给定字符之前的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61436867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com