dart正则表达式匹配并从中获取一些信息

时间:2013-05-13 13:11:02

标签: regex dart

对于练习,我决定构建类似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

关心给我一些指点吗?谢谢。

1 个答案:

答案 0 :(得分:7)

您需要将要提取的部分放入组中,以便从匹配中提取它们。这是通过将一部分模式放在括号内来实现的。

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

这可以确保正则表达式从字符串的开头到结尾完全锚定,而不仅仅是字符串中的任何位置。