首页 > 解决方案 > Groovy - 如何拆分包含多个文件名但其中一些包含空格的字符串?

问题描述

如何拆分包含多个文件名(包括包含空格的名称)的字符串?

示例字符串:

randomFolderNameA/path/to/file1.java randomFolderNameB/path/to/file2.sql randomFolderNameC/path/to/file3 with space.xml file4 with space.sql 

预期输出:

randomFolderNameA/path/to/file1.java
randomFolderNameB/path/to/file2.sql
randomFolderNameC/path/to/file3 with space.xml
file4 with space.sql 

标签: stringgroovysplit

解决方案


假设你所有的路径都是绝对的,你可以在你的正则表达式中使用前瞻断言:

def text = "/path/to/file1.java /path/to/file2.sql /path/to/file3 with space.xml"
println text.split(" (?=/)")

那输出[/path/to/file1.java, /path/to/file2.sql, /path/to/file3 with space.xml]

Taht 正则表达式将字符串拆分为一个空格,后跟一个/


编辑:对于更新的示例,可以查看文件名中的扩展名,尽管您需要仔细考虑您的输入可以包括什么:

def text = "randomFolderNameA/path/to/file1.java randomFolderNameB/path/to/file2.sql randomFolderNameC/path/to/file3 with space.xml file4 with space.sql"

println text.split("(?<=\\.[a-zA-Z0-9]{1,4}) ")

正如预期的那样,输出如下:

[randomFolderNameA/path/to/file1.java, 
 randomFolderNameB/path/to/file2.sql, 
 randomFolderNameC/path/to/file3 with space.xml, 
 file4 with space.sql]

但如上所述,您需要确保路径仅包含文件名并且扩展名正则表达式有效(我使用“一个点后跟 1 到 4 个字母数字字符”)


推荐阅读