簡體   English   中英

如何刪除字符串中的所有前導斜線?

[英]How to remove all leading slashes in a string?

我在Java中有一個字符串,它以斜杠開頭,但是斜杠的數量未知。 一開始如何刪除所有這些斜線?

例如:

String a="//abc";

應該輸出abc

String b="////abc";

還應該輸出abc

您可以為此使用簡單的模式:

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("");
}

訣竅是刪除前導斜杠,而不是所有斜杠。

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("^/+", ""));
}

輸出為:

ab / c

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM