skip to Main Content

I want to extract sub strings from a string using regex in flutter.

Eg: if string is "HI hello @shemeer how are you @nijin", the expected result will be [shemeer,nijin]

Input : String s= "HI hello @shemeer ul haq how are you @nijinsha rah"

Output: output=["shemeer ul haq","nijinsha rah"]

Is anybody knows it, please help me

2

Answers


  1. You can split the string into words and then look for @ and generate list based on it.

        final names = data
            .split(" ")
            .where((element) => element.startsWith("@"))
            .map((e) => e.substring(1))
            .toList();
    

    Or use allMatches with RegExp(r'@w+') as pskink mentioned on comment.

    final names = RegExp(r'@w+')
        .allMatches(data)
        .map((e) => e.group(0)!.substring(1))
        .toList();
    
    Login or Signup to reply.
  2. You could try to use this regex pattern: (?<=@)w+

    RegExp exp = RegExp(r'(?<=@)(w+)');
    String str = 'HI hello @shemeer how are you @nijin';
    Iterable<RegExpMatch> output = exp.allMatches(str);
    for (final m in output) {
      print(m[0]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search