首页 > 解决方案 > 正则表达式返回 null 或搜索表达式

问题描述

我试图11020001588_20210127175414319.wav从字符串中获取文件名file:////media//devion//recordings//voicemail//1/102/000/11020001588/11020001588_20210127175414319.wav

我使用的方法

regExtractFile(filepath) {
    RegExp filename = RegExp(
        (r'([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]).wav'));
    Iterable<RegExpMatch> matches = filename.allMatches(filepath);
    matches.forEach((match) {
      print(filename.toString().substring(match.start, match.end));
    });
  }

当我运行此方法时,我会得到类似的输出

I/flutter (18734): -9]_[0-9][0-9][0-9][0-9][0-9][0-9
I/flutter (18734): null
I/flutter (18734): -9]_[0-9][0-9][0-9][0-9][0-9][0-9
I/flutter (18734): null
I/flutter (18734): -9]_[0-9][0-9][0-9][0-9][0-9][0-9

我不能尝试 subString 来提取文件路径,因为所有字符串都不同,文件名是常见的,dart 和 regex 的新手,感谢所有帮助。

标签: regexflutterdart

解决方案


您可以使用路径来获取文件名

import 'package:path/path.dart' as filePath;
import 'dart:io';

先获取文件名

File file = new File("file:////media//devion//recordings//voicemail//1/102/000/11020001588/11020001588_20210127175414319.wav");
String basename = filePath.basename(file.path);

然后检查:

RegExp regExp = RegExp((r'([0-9]{11}\_[0-9]{17})\.wav'));
print("$filename ; hasMatch : ${regExp.hasMatch(filename)}");

我不确定这是你想要的


推荐阅读