dart regex matching and get some information from it dart regex matching and get some information from it dart dart

dart regex matching and get some information from it


You need to put the parts you want to extract into groups so you can extract them from the match. This is achieved by putting a part of the pattern inside parentheses.

// added parentheses around \w+ and \d+ to get separate groups String regexString = r'/api/(\w+)/(\d+)/'; // not r'/api/\w+/\d+/' !!!RegExp regExp = new RegExp(regexString);var matches = regExp.allMatches("/api/topic/3/");print("${matches.length}");       // => 1 - 1 instance of pattern found in stringvar match = matches.elementAt(0); // => extract the first (and only) matchprint("${match.group(0)}");       // => /api/topic/3/ - the whole matchprint("${match.group(1)}");       // => topic  - first matched groupprint("${match.group(2)}");       // => 3      - second matched group

however, the given regex would also match "/api/topic/3/ /api/topic/4/" as it is not anchored, and it would have 2 matches (matches.length would be 2) - one for each path, so you might want to use this instead:

String regexString = r'^/api/(\w+)/(\d+)/$';

This ensures that the regex is anchored exactly from beginning to the end of the string, and not just anywhere inside the string.