在此代码中,我们使用 .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();
关于java - 什么等同于 .replaceSecond 或 .replaceThird?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53372287/