java - 什么等同于 .replaceSecond 或 .replaceThird?

标签 java string replace

在此代码中,我们使用 .replaceFirst 方法从 email 字符串中删除子字符串“luna”。我们正在删除 + 和 @ 之间的字符。但这仅在第一个实例中发生,因为我们使用了 .replaceFirst。如果我们想针对 + 和 @ 的第二个实例来删除“smith”怎么办? 我们现在的输出是 alice+@john+smith@steve+oliver@ 但我们想要 alice+luna@john+@steve+oliver@

public class Main {

    public static void main(String[] args) {

        String email = "alice+luna@john+smith@steve+oliver@";

        String newEmail = email.replaceFirst("\\+.*?@", "");

        System.out.println(newEmail);

    }
}

最佳答案

你可以像这样找到第二个+:

int firstPlus = email.indexOf('+');
int secondPlus = email.indexOf('+', firstPlus + 1);

(如有必要,您需要处理没有两个 + 可查找的情况)。

然后找到下面的@:

int at = email.indexOf('@', secondPlus);

然后把它缝合起来:

String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);

String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();

Ideone demo

关于java - 什么等同于 .replaceSecond 或 .replaceThird?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53372287/

相关文章:

java - 在 Java 中持久化对象的轻量级方法

java - 这是 Java SynchronizedCollection 类中的错误吗?

C++ 字符串继承

python - 如何删除 DataFrame 字符串中的特殊字符(例如 ",")?

java - 如何从我的 Dropwizard 资源中访问已包装在自定义类中的请求?

database - 在 Perl 中将整数转换为字符串以进行数据库插入

string - 如何验证 JSF 表单上模式的字符串输入字段

javascript - 字符串替换表达式

JavaScript 替换字符

java - JPA/Hibernate - 删除子项会删除父项(从同一个表中)