dart regex匹配并从中获取一些信息 [英] dart regex matching and get some information from it
问题描述
对于实践,我决定建立一个像 Backbone
路由器。用户只需要提供正则表达式字符串,如 r'^ first / second / third / $'
,然后将它挂钩到 View
。
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
.
例如,假设我有一个 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
c $ c> HttRequest 指向 / api / topic / 1 /
并且匹配那个regex,然后我可以渲染任何钩子到那个url 。
And a HttRequest
point to /api/topic/1/
and that would match that regex, then i can rendered anything hook to that url.
问题是,从上面的正则表达式,我怎么知道 \w +
和 \d +
值为主题
和 1
。
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.
推荐答案
您需要将要提取的部分放入组中,以便从匹配中提取。
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
但是,给定的正则表达式也会匹配/ api / topic / 3 / / api / topic / 4 /
,因为它没有锚定,它会有两个匹配( matches.length
将会是2) - 每个路径一个,所以你可能想要改用:
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.
这篇关于dart regex匹配并从中获取一些信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!