string - 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
解决方案
假设你所有的路径都是绝对的,你可以在你的正则表达式中使用前瞻断言:
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 个字母数字字符”)
推荐阅读
- excel - VBA 错误 1004:Chart.ChartData.Workbook 对象的方法“关闭”失败
- flutter - 添加两个容器,一个用于文本,另一个用于 viewgrid
- sql - 如果不存在则创建数据库,然后在 SQL Server 中的该数据库中创建表
- jquery - 如何计算隐藏 div 内的可见集元素?
- python - 如何使用 Selenium 找到带有下划线的类?
- javascript - 造句只能包含数组内的字符
- c# - C# HTTPListener 服务器无法从 LAN 中的其他设备访问
- json - 从 json 的嵌套对象中获取值而不创建额外的类
- python - 如何使用 HDF5 存储和加载 Python 字典
- google-bigquery - IF Conditional to Run Schedule Query