对于实践中,我决定建立像一个Backbone
路由器。 用户只需要给正则表达式字符串如r'^first/second/third/$'
,然后钩住到一个View
。
例如,假设我有一个RegExp
是这样的:
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
和HttRequest
点/api/topic/1/
这将匹配正则表达式,那么我可以呈现什么勾到该网址。
问题是,从上述正则表达式,我怎么知道\w+
与\d+
值是topic
和1
。
关爱给我一些指点的人? 谢谢。
你需要把你想提取到组的部分,所以你可以从比赛提取它们。 这是通过把括号内的模式的一部分来实现的。
// 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
然而,给定的正则表达式也将匹配"/api/topic/3/ /api/topic/4/"
,因为它未锚定,并且将具有2个匹配( matches.length
将是2) -一个用于每个路径,所以你可能要改用这一点:
String regexString = r'^/api/(\w+)/(\d+)/$';
这确保了正则表达式是从一开始正是锚定在字符串的结尾,而不是随便找个地方里面的字符串。