在这段代码中,我们使用
.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);
}
}