Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

dart regex matching and get some information from it

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...