zoukankan      html  css  js  c++  java
  • 正则表达式(Dart)

    课题

    1. 使用正则表达式匹配字符串
      使用正则表达式 "d{3}-(d{4})-d{2}" 匹配字符串 "123-4567-89"
      返回匹配结果:’"123-4567-89" 以及 "4567"
    2. 使用正则表达式替换字符串(模式)
      使用正则表达式 "(d+)-(d+)-(d+)" 匹配字符串 "123-4567-89"
      使用模式字符串 "$3-$1-$2" 替换匹配结果,返回结果 "89-123-4567"。
    3. 使用正则表达式替换字符串(回调)
      使用正则表达式 "d+" 匹配字符串 "123-4567-89"
      将匹配结果即三个数字串全部翻转过来,返回结果 "321-7654-98"。
    4. 使用正则表达式分割字符串
      使用正则表达式 "%(begin|next|end)%" 分割字符串"%begin%hello%next%world%end%"
      返回正则表达式分隔符之间的两个字符串 "hello" 和 "world"。

    Dart

    void main() {
      final s = "123-4567-89,987-6543-21";
      final r = RegExp(r"d{3}-(d{4})-d{2}");
      final m = r.firstMatch(s);
      if (m != null) print("Found matches:");
      final ms = r.allMatches(s);
      ms.toList().asMap().forEach((i, m) {
        for (var j = 0; j <= m.groupCount; j++)
          print("group $i,$j : ${m.group(j)}");
      });
    
      print(s.replaceAllMapped(RegExp(r"(d+)-(d+)-(d+)"), (m) => "${m.group(3)}-${m.group(1)}-${m.group(2)}"));
    
      // https://stackoverflow.com/questions/21521729/how-do-i-reverse-a-string-in-dart
      print(s.replaceAllMapped(RegExp(r"d+"), (m) => m.group(0).split("").reversed.join()));
    
      print("%begin%hello%next%world%end%".split(RegExp("%(begin|next|end)%")));
    }
    
    /*
    Found matches:
    group 0,0 : 123-4567-89
    group 0,1 : 4567
    group 1,0 : 987-6543-21
    group 1,1 : 6543
    89-123-4567,21-987-6543
    321-7654-98,789-3456-12
    [, hello, world, ]
    */
    
  • 相关阅读:
    五一拆装机学习
    msgbox函数和inputbox函数应该注意的几点
    西游记(3)
    刚刚开通csdn
    c# 快捷键
    JavaBean的属性(Simple,Indexed,Bound,Constrained)【收藏】
    SQL查询语句使用【收藏】
    .NET 对实现IPersistStream接口的对象进行保存和读取
    创建控件数组
    常用数据库JDBC连接写法【收藏】
  • 原文地址:https://www.cnblogs.com/zwvista/p/13671860.html
Copyright © 2011-2022 走看看