Home > Mobile >  Extract template tags {{..}} from a string in flutter
Extract template tags {{..}} from a string in flutter

Time:08-10

I need to extract squiggly bracketed template tags from a string. For example:

String str="Hello {{user}}, your reference is {{ref}}"

I would like a to extract the tags in-between the {{..}} into an List. For example:

["user","ref"]

How can I do this, for example with a Regx - I would need to ignore any whitespace in-side the brackets for example {{ user}} would need to return "user".

This question is exactly same as this que.. Want code for flutter dart.

CodePudding user response:

You can use this regex

void main() {
  RegExp re = RegExp(r'{{([^]*?)}}');
  String data = "Hello {{user}}, your reference is {{ref}}";
  var match = re.firstMatch(data);
  if (match != null) print(match.group(1));
  List something = re.allMatches(data).map((m)=>m[1]).toList();
  print(something);
}

OUtput

user
[user, ref]

CodePudding user response:


void main() {
 
  String str="Hello {{user}}, your reference is {{ref}}";
  
  List<String> lstr = getStringBetweenBracket(str);
  print(lstr);
   
}

List<String> getStringBetweenBracket(String str) {
  
  List<String> rstr = [];
  var j = str.splitMapJoin(new RegExp(r'\{\{(.*?)\}\}'), onMatch: (e) {
    
    if( e.group(0) != null)
      return e.group(0)!.replaceAll("{{","").replaceAll("}}","") ",";
    else
      return "";
    
  }, onNonMatch: (e) { return ""; });
  
  if(j != "") {
    rstr = j.split(",");
    rstr.removeAt(rstr.length-1);
  }
  return rstr;
}

CodePudding user response:

    you can do this way get array of data
    
    void main()  {
    String str="Hello {{user}}, your reference is {{ref}}";
    var parts = str.split(' ');
      print(parts);
      print(parts[1]);
    }


void main(){
     
    String str = 'HelloTutorialKart.';
     
    int startIndex = 5;
    int endIndex = 13;
     
    //find substring
    String result = str.substring(startIndex, endIndex);
     
    print(result);
}

output

Tutorial
  • Related