省道正则表达式匹配,并从它那里得到一些信息(dart regex matching and get

2019-09-02 21:25发布

对于实践中,我决定建立像一个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+值是topic1

关爱给我一些指点的人? 谢谢。

Answer 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+)/$';

这确保了正则表达式是从一开始正是锚定在字符串的结尾,而不是随便找个地方里面的字符串。



文章来源: dart regex matching and get some information from it
标签: regex dart