gpt4 book ai didi

Java 删除除某些内容之外的所有内容

转载 作者:行者123 更新时间:2023-12-02 07:15:59 25 4
gpt4 key购买 nike

这是一些代码:

    String cakes = "I like to eat ice cream sandwiches at night";
cakes = cakes.replace("ice cream", "");
System.out.println(cakes);

这会删除冰淇淋。凉爽的。但我想要的是:

    String cakes = "I like to eat ice cream sandwiches at night";
cakes = "ice" thru "sandwiches";
System.out.println(cakes);

这个弥补操作要做的就是删除除冰和三明治之间的字母之外的所有内容,使线状蛋糕成为“ Ice Cream Sandwich ”。这可能吗?

编辑:我有一个新代码:

    String cakes = "I like to eat ice cream sandwiches at night";
String ice = "ice";
String sandwiches = "sandwiches";
cakes = cakes.substring(cakes.indexOf(ice),cakes.indexOf(sandwiches)+sandwiches.length());

System.out.println(cakes);

这可行,但有一个问题:对于 cake 的某些值(例如网站的 html 代码),我收到错误:

          Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -number
at java.lang.String.substring(Unknown Source)
at package.cclass.main(cat.java:31)

最佳答案

为此我想到了正则表达式。

这篇文章有一个在 Java 中使用正则表达式的示例:Java regex to remove all trailing numbers?

在这种情况下,表达式将类似于:“ice.*sandwiches”

编辑:我以为我们要删除这些词。我的错。这里有一些代码应该可以完成您正在寻找的更多功能。

Pattern p = Pattern.compile("ice.*sandwiches");
Matcher m = p.matcher("I like to eat ice cream sandwiches at night");
while (m.find()) {
String s = m.group(1);
}

关于Java 删除除某些内容之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14942463/

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