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

标签 java regex file cross-platform

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

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/

相关文章:

java - 如何在 Java 中使用 PDFBox 获取 PDF 文件中的所有书签

c# - 正则表达式提取多个句子,同时丢弃特定句子

JavaScript .search() 使用正则表达式查找带有通配符的 URL

python - 使用 'exec' 函数在解释器 Shell 中运行脚本

java - 如何在 Hibernate XML 配置文件中使用属性表示法

java - 如何居中 TChart 标题?

java - 哪个性能更好?在 Java 中使用 .properties 文件或 .conf 文件?

java - 快速重绘 map 的有效方法(Java/JPanel)

javascript - 使用正则表达式获取 url 变量

python - 如何在 Mac 上通过 Python 在 TextEdit 中打开文本文件?