Dart中移除列表内字符串指定前缀以获取文件名
需求与处理方案
原始需求
移除列表中每个字符串的指定前缀:
- 第一个字符串需移除前缀
{2: - 其余字符串需移除数字+空格前缀部分
最终仅保留文件名。
原始列表内容
{2: test1.mp4 3: test2.mp4 4: test3.mp4 10: test4.mp4 11: test5.mp4
处理后的结果
- test1.mp4
- test2.mp4
- test3.mp4
- test4.mp4
- test5.mp4
批量实现方法(Python示例)
使用正则表达式可统一处理所有条目,无需单独区分第一个项:
import re # 原始数据 raw_lines = [ "{2: test1.mp4", "3: test2.mp4", "4: test3.mp4", "10: test4.mp4", "11: test5.mp4" ] # 批量清理前缀 cleaned_files = [re.sub(r'^\{?\d+: ', '', line) for line in raw_lines] # 输出结果 for filename in cleaned_files: print(filename)
正则表达式说明
^\{?\d+: 可匹配所有目标前缀:
^匹配字符串起始位置\{?匹配可选的左大括号(兼容第一个条目的格式)\d+匹配1个或多个数字:匹配冒号加空格的固定分隔符
内容的提问来源于stack exchange,提问作者swigswag
相关产品推荐
相关产品推荐

