简体   繁体   中英

How to remove all leading slashes in a string?

I have a string in Java, it starts with slashes, but the number of slashes is unknown. How can I remove all theses slashes at start?

For example:

String a="//abc";

Should output abc .

String b="////abc";

Should also output abc .

You can use a simple pattern for that:

private static final Pattern HEADING_SLASHES = Pattern.compile("^/+");

// ...

public static String removeHeadingSlashes(final String input)
{
    // .replaceFirst() or .replaceAll() will have the same effect, so...
    return HEADING_SLASHES.matcher(input).replaceFirst("");
}

The trick is to remove the leading slashes, not all slashes.

public class StringTest {

    public static void main(String[] args) {
        String url = "////abc//def";
        System.out.println(url.replaceFirst("/+", ""));
    }

}
public static void main(String[] args) {
    String slashString = "//ab/c";

    System.out.println(slashString.replaceAll("^/+", ""));
}

output is:

ab/c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM