【问题标题】:Flutter - How to replace text (containing "id") with title for the id?Flutter - 如何用 id 的标题替换文本(包含 \"id\")?
【发布时间】:2023-01-12 16:12:17
【问题描述】:

我有这样的文字:

Forecaster 强烈反对\n\n还会发生其他事情\n\n示例:-\n\n#:hashtag/424 \n#:hashtag/2818 ",

我需要获取 424 和 2818(它们是 ID)并找到这些 ID 的标题并将#:hashtag/424 替换为#Title1

我如何为此操作字符串?

【问题讨论】:

    标签: regex string flutter dart replace


    【解决方案1】:

    您可以使用这样的正则表达式:

      RegExp exp = RegExp(r'#:hashtag/(d+)');
      String test = "Forecaster Strongly disagree 
    
    Something else is going to happen
    
    Example:-
    
    #:hashtag/424 
    #:hashtag/2818";
    
      final matches = exp.allMatches(test);
      
      if(matches.isNotEmpty){
        print (matches.first[0]!.split('/').last);
      }
    //prints 424
    

    根据您对输入字符串的期望,可能需要进行一些额外的空值检查

    要替换 ID,您可以使用 replaceAllMapped 方法,如下所示:

      test.replaceAllMapped(exp, (match) => match[0]!.split('/').first + '/#Title1');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 2014-03-06
      • 2015-02-21
      相关资源
      最近更新 更多