【问题标题】:Regex: Duration (hours, minutes) in dart正则表达式:飞镖中的持续时间(小时,分钟)
【发布时间】:2020-02-15 18:55:16
【问题描述】:

我正在尝试使用 RegEx 对数据列表进行排序。目前,下面的代码只检查小时和分钟。

当前输出示例:

1:22:00.000000

但我有一些数据也只有几分钟或几小时。

我正在寻找编辑此代码,以便检查所有这些可能性:

  • 小时

  • 分钟

  • 小时和分钟

final _regExp = RegExp(r'(?<hours>\d+)h (?<minutes>\d+)m');
Duration _parseDuration(String line) {
  final match = _regExp.firstMatch(line);

  if (match == null) {
    throw Exception('Could not get duration from: $line');
  }

  return Duration(
      hours: int.parse(match.namedGroup('hours')),
      minutes: int.parse(match.namedGroup('minutes')));
}

我不知道该怎么做?

任何帮助将不胜感激。

【问题讨论】:

  • 您能否举例说明您输入的不同形式以及您期望的结果。没有一些测试数据,很难做出一个固溶体。 :)
  • 不确定是否可以为捕获组使用相同的名称,但可以使用替代名称(?:(?:(\d+)h )?(\d+)m|(?:(\d+)h))regex101.com/r/uSn0sL/1

标签: regex dart


【解决方案1】:

不确定您是否可以为捕获组使用相同的名称,但您可以使用替换来匹配可选的小时和分钟或小时。

(?:(?:(\d+)h )?(\d+)m|(\d+)h)
  • (?:非捕获组
    • (?:(\d+)h )? 捕获group 1,匹配可选数字和h
    • (\d+)m 捕获 第 2 组,匹配 1+ 个数字和 m
    • |或者
    • (\d+)h 捕获组 3,匹配 1+ 位和 h
  • )关闭群

Regex demo | Dart demo

小时在第 1 组或第 3 组,分钟在第 2 组。

我对 Dart 不熟悉,所以可能有更好的方法来编写它,但是为了这个想法,我添加了一个示例。

final _regExp = RegExp(r'(?:(?:(\d+)h )?(\d+)m|(\d+)h)');
Duration _parseDuration(String line) {
  final match = _regExp.firstMatch(line);

  if (match == null) {
    throw Exception('Could not get duration from: $line');
  }
  String h = match.group(1) ?? match.group(3) ?? "00";
  String m = match.group(2) ?? "00";


  return Duration(
      hours: int.parse(h),
      minutes: int.parse(m));
}

【讨论】:

    【解决方案2】:

    我想这会奏效。我刚刚添加,所以每个组都是可选的,如果输入中没有任何组,则使用值 0:

    void main() {
      print(_parseDuration('5h'));      // 5:00:00.000000
      print(_parseDuration('5m'));      // 0:05:00.000000
      print(_parseDuration('10h 50m')); // 10:50:00.000000
    }
    
    final _regExp = RegExp(r'((?<hours>\d+)h)?[ ]*((?<minutes>\d+)m)?');
    Duration _parseDuration(String line) {
      final match = _regExp.firstMatch(line);
    
      if (match == null) {
        throw Exception('Could not get duration from: $line');
      }
    
      return Duration(
          hours: int.parse(match.namedGroup('hours') ?? '0'),
          minutes: int.parse(match.namedGroup('minutes') ?? '0'));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      • 2019-01-31
      • 1970-01-01
      • 2020-09-08
      相关资源
      最近更新 更多