String starts with

The string ends with example will check if a string ends with a specified String while this example will show how to check if a string starts with a specified prefix using java, regular expression, apache commons and springframework. Each snippet will contain a String that represents a URL address and will validate that it starts with http.

Straight up Java

Starts with

This snippet will demonstrate how to use the String.startsWith method. The startWith method will return true if the argument is the prefix of the String or false otherwise.

@Test
public void string_starts_with_java () {

    boolean startsWithHttp = "http://www.leveluplunch.com".startsWith("http");

    assertTrue(startsWithHttp);
}

Starts with regex

We can also can pass a regular expression to the String.startWith.

@Test
public void string_starts_with_regular_expression_with_java () {

    boolean startsWithHttpsOrFTP = "http://www.leveluplunch.com"
            .startsWith("^(https?|ftp)://.*$");

    assertFalse(startsWithHttpsOrFTP);
}

Apache Commons

Starts with

Apache commons StringUtils.startsWith will check if a CharSequence starts with a specified prefix and returning true if it does, otherwise false.

@Test
public void string_starts_with_apache_commons() {

    boolean startsWithHttp = StringUtils.startsWith(
            "http://www.leveluplunch.com", "http");

    assertTrue(startsWithHttp);
}

Starts with any

Another useful method contained in apache commons is StringUtils.startsWithAny. This will perform the same behavior as the startsWith but instead of checking a single value, it will compare against a series of specified strings contained in the array.

@Test
public void string_starts_with_any_apache_commons() {

    boolean startsWithHttpProtocol = StringUtils
            .startsWithAny("http://www.leveluplunch.com", new String[] {
                    "http", "https" });

    assertTrue(startsWithHttpProtocol);
}

Spring Framework

Each of the snippets above are case sensitive while the spring framework code is a bit different. Calling the StringUtils.startsWithIgnoreCase will check if it starts with a character but will ignore the upper and lower case.

@Test
public void string_starts_with_spring () {

    boolean startsWithHttp = org.springframework.util.StringUtils
            .startsWithIgnoreCase("http://www.leveluplunch.com", "http");

    assertTrue(startsWithHttp);
}