美文网首页
flutter字符串多个批量查找和替换

flutter字符串多个批量查找和替换

作者: xmb | 来源:发表于2021-03-11 17:02 被阅读0次

使用方法:splitMapJoin

替换前:
<video controls='controls' type='video/mp4' src='/s1/2020/7/23/ca226be9814208db75cf000eb43cf12f.mp4'></video>
<iframe class='ql-video' frameborder='0' allowfullscreen='true' src='/s1/2020/7/23/ca226be9814208db75cf000eb43cf12f.mp4'></iframe>
替换后:
<video controls='controls' type='video/mp4'><source src='/s1/2020/7/23/ca226be9814208db75cf000eb43cf12f.mp4' /></video>
<video controls='controls' type='video/mp4'><source src='/s1/2020/7/23/ca226be9814208db75cf000eb43cf12f.mp4' /></video>
代码:
class HtmlUtils {
  /// 替换html中的video和iframe为html插件可识别的标签
  static String changeVideoTag(String originHtmlString) {
    /**
     * 替换之前
     * <video controls='controls' type='video/mp4' src='/s1/2020/7/23/ca226be9814208db75cf000eb43cf12f.mp4'></video>
     * 替换之后
     * <video controls='controls' type='video/mp4'><source src='/s1/2020/7/23/ca226be9814208db75cf000eb43cf12f.mp4' /></video>
     */

    /**
     * 替换之前
     * <iframe class='ql-video' frameborder='0' allowfullscreen='true' src='/s1/2020/7/23/ca226be9814208db75cf000eb43cf12f.mp4'></iframe>
     * 替换之后
     * <video controls='controls' type='video/mp4'><source src='/s1/2020/7/23/ca226be9814208db75cf000eb43cf12f.mp4' /></video>
     */

    return originHtmlString.splitMapJoin(
      RegExp('\\<video([\\s\\S]*?)\\</video>'),
      onMatch: (text) {
        // print('查询到的字符串:${text.group(0)}');
        String matchString = text.group(0);

        // 获取src字符串
        String srcString = matchString.split('src=\'')[1].split('\'')[0];
        print('srcString:$srcString');

        // 方法一
        // matchString = matchString.replaceFirst('src=\'', '><source src=\'');
        // matchString = matchString.replaceFirst('\'><', '\' /><');

        // 方法二
        matchString = "<video controls='controls' type='video/mp4'><source src='$srcString' /></video>";

        return matchString;
      },
      onNonMatch: (text) {
        return text;
      },
    ).splitMapJoin(
      RegExp('\\<iframe([\\s\\S]*?)\\</iframe>'),
      onMatch: (text) {
        // print('查询到的字符串:${text.group(0)}');
        String matchString = text.group(0);

        // 获取src字符串
        String srcString = matchString.split('src=\'')[1].split('\'')[0];
        // print('srcString:$srcString');

        return "<video controls='controls' type='video/mp4'><source src='$srcString' /></video>";
      },
      onNonMatch: (text) {
        return text;
      },
    );
  }
}

相关文章

网友评论

      本文标题:flutter字符串多个批量查找和替换

      本文链接:https://www.haomeiwen.com/subject/wnkoqltx.html