Remove or Replace part of a String in Java – 在Java中删除或替换一个字符串的一部分

最后修改: 2018年 11月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’re going to be looking at various means we can remove or replace part of a String in Java.

在本教程中,我们将研究在Java中删除或替换部分String的各种方法。

We’ll explore removing and/or replacing a substring using a String API, then using a StringBuilder API and finally using the StringUtils class of Apache Commons library.

我们将探索使用String API删除和/或替换一个子串,然后使用StringBuilder API,最后使用Apache Commons库的StringUtils类。

As a bonus, we’ll also look into replacing an exact word using the String API and the Apache Commons RegExUtils class.

作为奖励,我们还将研究使用字符串API和Apache Commons的RegExUtils类来替换一个精确的单词

2. String API

2.String API

One of the simplest and straightforward methods of replacing a substring is using the replace, replaceAll or replaceFirst of a String class.

替换子串的最简单直接的方法之一是使用字符串类的replace, replaceAllreplaceFirst

The replace() method takes two arguments – target and replacement text:

replace()方法需要两个参数 – 目标和替换文本。

String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";
String processed = master.replace(target, replacement);
assertTrue(processed.contains(replacement));
assertFalse(processed.contains(target));

The above snippet will yield this output:

上述片段将产生这样的输出。

Hello World Java!

If a regular expression is required in choosing the target, then the replaceAll() or replaceFirst() should be the method of choice. As their name implies, replaceAll() will replace every matched occurrence, while the replaceFirst() will replace the first matched occurrence:

如果在选择目标时需要一个正则表达式,那么replaceAll()replaceFirst()应该是选择的方法。顾名思义,replaceAll()将替换每个匹配的出现,而replaceFirst()将替换第一个匹配的出现。

String master2 = "Welcome to Baeldung, Hello World Baeldung";
String regexTarget = "(Baeldung)$";
String processed2 = master2.replaceAll(regexTarget, replacement);
assertTrue(processed2.endsWith("Java"));

The value of processed2 will be:

processed2的值将是。

Welcome to Baeldung, Hello World Java

It’s because the regex supplied as regexTarget will only match the last occurrence of Baeldung. In all examples given above, we can use an empty replacement and it’ll effectively remove a target from a master.

这是因为作为regexTarget提供的regex将只匹配Baeldung的最后出现。在上面给出的所有例子中,我们可以使用一个空的替换,它将有效地从master中删除一个target

3. StringBuilder API

3.StringBuilder API

We can also manipulate text in Java using the StringBuilder classThe two methods here are delete() and replace().

我们还可以使用StringBuilder 在Java中操作文本。这里的两个方法是delete()replace()

We can construct an instance of a StringBuilder from an existing String and then use the methods mentioned to perform the String manipulation as desired:

我们可以从现有的String构造一个StringBuilder的实例,然后使用所提到的方法来进行所需的String操作。

String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";

int startIndex = master.indexOf(target);
int stopIndex = startIndex + target.length();

StringBuilder builder = new StringBuilder(master);

Now we can remove the target with the delete():

现在我们可以用delete()来删除target

builder.delete(startIndex, stopIndex);
assertFalse(builder.toString().contains(target));

We can as well use the replace() to update the master:

我们也可以使用replace()来更新master。

builder.replace(startIndex, stopIndex, replacement);
assertTrue(builder.toString().contains(replacement));

One apparent difference between using the StringBuilder and the String API is that we’ve to get the start and the stop index of the target String ourselves.

使用StringBuilderString API的一个明显区别是,我们必须自己获得target String的起始和停止索引。

4. StringUtils Class

4.StringUtils

Another method we’ll consider is the Apache Commons library.

我们要考虑的另一种方法是Apache Commons库。

First, let’s add the required dependency to our project:

首先,让我们把所需的依赖性添加到我们的项目中。

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

The latest version of the library can be found here.

最新版本的库可以在这里找到。

The StringUtils class has methods for replacing a substring of a String:

StringUtils类拥有替换String子串的方法。

String master = "Hello World Baeldung!";
String target = "Baeldung";
String replacement = "Java";

String processed = StringUtils.replace(master, target, replacement);
assertTrue(processed.contains(replacement));

There is an overloaded variant of the replace() that takes an integer max parameter, which determines the number of occurrences to replace. We can also use the replaceIgnoreCase() if case-sensitivity is not a concern:

replace()有一个重载的变体,它需要一个整数max参数,这决定了要替换的出现的数量。如果不考虑大小写敏感度,我们也可以使用replaceIgnoreCase()

String master2 = "Hello World Baeldung!";
String target2 = "baeldung";
String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
assertFalse(processed2.contains(target));

5. Replacing Exact Words

5.替换准确的字词

In this last example, we’ll learn how to replace an exact word inside a String.

在这最后一个例子中,我们将学习如何替换String内的一个确切的单词。

The straightforward way to perform this replacement is using a regular expression with word boundaries.

执行这种替换的直接方法是使用一个有词界的正则表达式

The word boundary regular expression is \b. Enclosing the desired word inside this regular expression will only match exact occurrences.

单词边界正则表达式是/b。在这个正则表达式中包含所需的词,将只匹配精确出现的词。

First, let’s see how to use this regular expression with the String API:

首先,让我们看看如何用字符串API来使用这个正则表达式。

String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!";
String regexTarget = "\\bcar\\b";
String exactWordReplaced = sentence.replaceAll(regexTarget, "truck");

The exactWordReplaced string contains:

exactWordReplaced字符串包含。

"A truck is not the same as a carriage, and some planes can carry cars inside them!"

Only the exact word will be replaced. Notice backward slash always needs to be escaped when working with regular expressions in Java.

只有准确的单词才会被替换。注意在Java中使用正则表达式时,反斜线总是需要被转义

An alternate way to do this replacement is using the RegExUtils class from the Apache Commons Library, which can be added as a dependency as we saw in the previous section:

另一种方法是使用Apache Commons Library中的RegExUtils类来进行替换,正如我们在上一节中看到的那样,它可以作为一个依赖项被添加。

String regexTarget = "\\bcar\\b";
String exactWordReplaced = RegExUtils.replaceAll(sentence, regexTarget, "truck");

While both methods will yield the same result, deciding which one should be used will depend on our specific scenario.

虽然这两种方法会产生相同的结果,但决定应该使用哪种方法将取决于我们的具体情景。

6. Conclusion

6.结论

In conclusion, we’ve explored more than one way of removing and replacing a substring in Java. The best method to apply still largely depends on the current situation and context.

总之,我们已经探索了在Java中删除和替换子串的不止一种方法。应用的最佳方法在很大程度上仍然取决于当前的情况和背景。

As usual, the complete source code is available over on Github.

像往常一样,完整的源代码可在Github上获得。