我正在使用以下代码从给定路径获取包含所有子目录的数组。
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 specifiedString
. This method produces aString
that can be used to create aPattern
that would match the strings
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 specifiedString
. This method produces aString
that will work as a literal replacements
in theappendReplacement
method of theMatcher
class. TheString
produced will match the sequence of characters ins
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
这个引用替换 String
在 String.replaceFirst
和 String.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. UseMatcher.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/