How to Remove a Prefix From Strings in Groovy – 如何在Groovy中删除字符串中的前缀

最后修改: 2020年 9月 18日

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

1. Introduction

1.绪论

In this quick tutorial, we’ll learn how to remove the prefix from a string in Groovy.

在这个快速教程中,我们将学习如何在Groovy中移除字符串的前缀。

First, we’ll look at what the String class offers for this purpose. After that, we’ll move on to regular expressions and see how we can use them to remove a prefix.

首先,我们将看看String类为这个目的提供了什么。之后,我们将转到正则表达式,看看我们如何使用它们来删除前缀。

2. Using String Methods

2.使用字符串方法

Generally, Groovy is considered a dynamic language for the Java ecosystem. Therefore, we can still use every Java String class method along with new Groovy ones. However, for the removal of the prefix, there is still an absence of a straightforward method like removePrefix().

一般来说,Groovy被认为是Java生态系统中的一种动态语言。因此,我们仍然可以在使用每一个JavaString类方法的同时使用新的Groovy方法。然而,对于去除前缀,仍然缺乏像removePrefix()这样直接的方法。

Removing of a prefix from Groovy strings consists of two steps: first confirmation and then removal. Both of these steps can be performed using the StringGroovyMethods class that offers many utility methods for string manipulations.

从Groovy字符串中删除前缀包括两个步骤:首先确认,然后删除。这两个步骤都可以使用StringGroovyMethods类来完成,该类提供了许多字符串操作的实用方法。

2.1. startsWith() Method

2.1.startsWith()方法

The startWith() method tests if a string starts with a specific prefix. It returns true if the prefix exists and false otherwise.

startWith()方法测试一个字符串是否以一个特定的前缀开始。如果前缀存在,它将返回true,否则返回false

Let’s start with a groovy closure:

让我们从一个groovy闭包开始。

@Test 
public void whenCasePrefixIsRemoved_thenReturnTrue(){
    def trimPrefix = {
        it.startsWith('Groovy-') ? it.minus('Groovy-') : it 
    }
    def actual = trimPrefix("Groovy-Tutorials at Baeldung")
    def expected = "Tutorials at Baeldung"
    assertEquals(expected, actual)
}

Once existence is confirmed, then we can also use the substring() method to remove it:

一旦确认存在,那么我们也可以使用substring()方法来删除它。

trimPrefix.substring('Groovy-'.length())

2.2. startsWithIgnoreCase() Method

2.2.startsWithIgnoreCase()方法

The startsWith() method is case-sensitive. So, a manual effort is required to negate the effect of the case either by applying the toLowerCase() or toUpperCase() methods.

startsWith()方法是大小写敏感的。因此,需要手动操作,通过应用toLowerCase()toUpperCase()方法来否定大小写的影响。

As the name suggests, the startsWithIgnoreCase() searches a prefix without case consideration. It returns true if a prefix exists and false otherwise.

顾名思义,startsWithIgnoreCase() 搜索前缀时不考虑大小写。如果有前缀存在,它返回true,否则返回false。

Let’s look at how to use this method:

我们来看看如何使用这种方法。

@Test
public void whenPrefixIsRemovedWithIgnoreCase_thenReturnTrue() {

    String prefix = "groovy-"
    String trimPrefix = "Groovy-Tutorials at Baeldung"
    def actual
    if(trimPrefix.startsWithIgnoreCase(prefix)) {
        actual = trimPrefix.substring(prefix.length())
    }

    def expected = "Tutorials at Baeldung"

    assertEquals(expected, actual)
}

2.3. startsWithAny() Method

2.3.startsWithAny()方法

The above solutions are useful when we have to check only one prefix. When it comes to checking multiple prefixes, Groovy also provides support to check multiple prefixes.

当我们只需要检查一个前缀时,以上的解决方案是很有用的。当涉及到检查多个前缀时,Groovy也提供了检查多个前缀的支持。

The startsWithAny() method checks if the CharSequence starts with any specified prefixes. Once the prefix is confirmed, we can apply logic according to requirements:

startsWithAny()方法检查CharSequence是否以任何指定前缀开始。一旦确认了前缀,我们可以根据要求应用逻辑。

String trimPrefix = "Groovy-Tutorials at Baeldung"
if (trimPrefix.startsWithAny("Java", "Groovy", "Linux")) {
    // logic to remove prefix
}

3. Using Regex

3.使用Regex

A regular expression is a powerful way to match or replace a pattern. Groovy has a pattern operator ~ that provides a simple way to create a java.util.regex.Pattern instance.

正则表达式是一种匹配或替换模式的强大方式。Groovy有一个模式操作符~,它提供了一个简单的方法来创建java.util.regex.Pattern实例。

Let’s define a simple regular expression to remove a prefix:

让我们定义一个简单的正则表达式来删除一个前缀。

@Test
public void whenPrefixIsRemovedUsingRegex_thenReturnTrue() {

    def regex = ~"^groovy-"
    String trimPrefix = "groovy-Tutorials at Baeldung"
    String actual = trimPrefix - regex

    def expected = "Tutorials at Baeldung"
    assertEquals("Tutorials at Baeldung", actual)
}

The case-insensitive version of the above regular expression:

上述正则表达式的不区分大小写的版本。

def regex = ~"^([Gg])roovy-"

The caret operator ^ will make sure that the specified substring exists at the start.

圆点运算符^将确保指定的子串在开始时存在。

3.1. replaceFirst() Method

3.1.replaceFirst()方法

Using regular expressions along with native strings methods, we can perform very powerful tricks. The replaceFirst() method is one of these methods. It replaces the first occurrence that matches the given regular expression.

使用正则表达式和本地字符串方法,我们可以执行非常强大的技巧。replaceFirst()方法就是这些方法之一。它替换了第一个与给定的正则表达式相匹配的出现。

Let’s remove a prefix using the replaceFirst() method:

让我们使用replaceFirst()方法删除一个前缀。

@Test
public void whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue() {

    def regex = ~"^groovy"
    String trimPrefix = "groovyTutorials at Baeldung's groovy page"
    String actual = trimPrefix.replaceFirst(regex, "")

    def expected = "Tutorials at Baeldung's groovy page"
    assertEquals(expected, actual)
}

3.2. replaceAll() Method

3.2.replaceAll()方法

Just like replaceFirst(), the replaceAll() also accepts a regular expression and given replacement. It replaces each substring that matches the given criteria. To remove a prefix, we can use this method too.

就像replaceFirst()一样,replaceAll()也接受一个正则表达式和给定的替换。它替换每个符合给定条件的子串。要删除一个前缀,我们也可以使用这个方法。

Let’s use replaceAll() to replace a substring at the start of the string only:

让我们使用replaceAll()来只替换字符串开头的子串。

@Test
public void whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue() {

    String trimPrefix = "groovyTutorials at Baeldung groovy"
    String actual = trimPrefix.replaceAll(/^groovy/, "")

    def expected = "Tutorials at Baeldung groovy"
    assertEquals(expected, actual)
}

4. Conclusion

4.总结

In this quick tutorial, we explored several ways to remove prefixes from a string. To confirm the existence of a prefix, we saw how to do this for both uppercase and lowercase strings.

在这个快速教程中,我们探讨了从字符串中删除前缀的几种方法。为了确认前缀的存在,我们看到了如何对大写和小写字符串进行处理。

At the same time, we’ve seen how to detect a prefix among many provided substrings. We also looked at multiple methods that can be used to remove a substring. Lastly, we briefly discussed the role of regex for this purpose.

同时,我们已经看到了如何在许多提供的子串中检测一个前缀。我们还看了可以用来删除一个子串的多种方法。最后,我们简要地讨论了regex在这方面的作用。

As always, all the code examples can be found over on GitHub.

一如既往,所有的代码实例都可以在GitHub上找到