gpt4 book ai didi

java - 如何拆分平台独立的路径?

转载 作者:太空狗 更新时间:2023-10-29 22:36:24 26 4
gpt4 key购买 nike

我正在使用以下代码从给定路径获取包含所有子目录的数组。

String[] subDirs = path.split(File.separator); 

我需要数组来检查某些文件夹是否位于此路径中的正确位置。这看起来是一个很好的解决方案,直到 findBugs 提示 File.separator 被用作正则表达式。似乎将 Windows 文件分隔符传递给从中构建正则表达式的函数是一个坏主意,因为反斜杠是转义字符。

如何在不使用 File.separator 的情况下跨平台拆分路径?或者这样的代码可以吗?

String[] subDirs = path.split("/"); 

最佳答案

文字化模式字符串

每当您需要字面化一个任意String 以用作正则表达式模式时,请使用Pattern.quote。 :

来自 API:

public static String quote(String s)

Returns a literal pattern String for the specified String. This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning.

Parameters: s - The string to be literalized
Returns: A literal string replacement

这意味着您可以执行以下操作:

String[] subDirs = path.split(Pattern.quote(File.separator));

文字化替换字符串

如果您需要文字化任意替换 String,请使用 Matcher.quoteReplacement .

来自 API:

public static String quoteReplacement(String s)

Returns a literal replacement String for the specified String. This method produces a String that will work as a literal replacement s in the appendReplacement method of the Matcher class. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.

Parameters: s - The string to be literalized
Returns: A literal string replacement

这个引用替换 StringString.replaceFirstString.replaceAll 中也很有用:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Use Matcher.quoteReplacement to suppress the special meaning of these characters, if desired.


例子

    System.out.println(
"O.M.G.".replaceAll(".", "!")
); // prints "!!!!!!"

System.out.println(
"O.M.G.".replaceAll(Pattern.quote("."), "!")
); // prints "O!M!G!"

System.out.println(
"Microsoft software".replaceAll("so", "$0")
); // prints "Microsoft software"

System.out.println(
"Microsoft software".replaceAll("so", Matcher.quoteReplacement("$0"))
); // prints "Micro$0ft $0ftware"

关于java - 如何拆分平台独立的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1099859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com