簡體   English   中英

正則表達式或String操作可從String派生自動模塊名稱

[英]Regex or String operation to derive automatic module name from String

我需要找到給定字符串名稱的自動模塊名稱,如下所示:

"common-io-1.2.3.jar" -> "common.io"
"---apple...orange..jar" -> "apple.orange"
"google-api-v1-beta.jar" -> "google.api.v1.beta"

我知道我可以使用ModuleFinder.of(Path)但是我的要求是在沒有任何文件系統IO的情況下派生它。

到目前為止,我發現:

在源代碼中ModuleFinder.of()工作方式 ,我發現了此方法 ,但這對於我所需要的來說實在太多了。

如何使用簡單的Regex或字符串操作來做到這一點?

遵循 JavaDoc:

public static String deriveModule(String filename) {

    // strip ".jar" at the end
    filename = filename.replaceAll("\\.jar$", "");

    // drop everything after the version
    filename = filename.replaceAll("-\\d.*", "");

    // all non alphanumeric get's converted to "."
    filename = filename.replaceAll("[^A-Za-z0-9]", ".");

    // strip "." at beginning and end
    filename = filename.replaceAll("^\\.*|\\.*$", "");

    // all double "." stripped to single
    filename = filename.replaceAll("\\.{2,}", ".");


    return filename;
}

您還可以檢查它是否是有效的模塊名稱:

public static boolean isValidModuleName(String name) {
    String VALID_REGEX = "([\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*";


    if (!name.matches(VALID_REGEX))
        return false;


    Set<String> keywords = Set.of("abstract", "continue", "for", "new", 
                    "switch", "assert", "default", "goto", "package",
                    "synchronized", "boolean", "do", "if", "private", "this",
                    "break", "double", "implements","protected", "throw", 
                    "byte", "else", "import", "public", "throws", "case", 
                    "enum", "instanceof", "return", "transient", "catch", 
                    "extends",  "int", "short", "try", "char", "final",
                    "interface", "static", "void", "class", "finally", 
                    "long", "strictfp", "volatile", "const",
                    "float", "native", "super", "while", "module", "open", 
                    "opens", "exports", "requires",
                    "transitive", "to", "with", "provides", "uses");


    String[] tokens = name.split("\\.");
    for (String t : tokens) {
        if (keywords.contains(t))
            return false;
    }

    return true;
}

暫無
暫無

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

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