Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart regex matching and get some information from it

Tags:

regex

dart

For practice, I decided to build something like a Backbone router. The user only needs to give the regex string like r'^first/second/third/$' and then hook that to a View.

For Example, suppose I have a RegExp like this :

String regexString = r'/api/\w+/\d+/';
RegExp regExp = new RegExp(regexString);
View view = new View(); // a view class i made and suppose that this view is hooked to that url

And a HttRequest point to /api/topic/1/ and that would match that regex, then i can rendered anything hook to that url.

The problem is, from the regex above, how do i know that \w+ and \d+ value is topic and 1.

Care to give me some pointers anyone? Thank you.

like image 513
Faris Nasution Avatar asked May 13 '13 13:05

Faris Nasution


1 Answers

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 string
var match = matches.elementAt(0); // => extract the first (and only) match
print("${match.group(0)}");       // => /api/topic/3/ - the whole match
print("${match.group(1)}");       // => topic  - first matched group
print("${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.

like image 113
Zdeslav Vojkovic Avatar answered Sep 20 '22 02:09

Zdeslav Vojkovic