dart 正则表达式匹配并从中获取一些信息 [英] dart regex matching and get some information from it

查看:176
本文介绍了dart 正则表达式匹配并从中获取一些信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了练习,我决定构建一个类似于 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 :

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

并且一个 HttRequest 指向 /api/topic/1/ 并且这将匹配那个正则表达式,然后我可以呈现任何钩子到那个 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+ 值是 topic1.

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/" 因为它没有锚定,并且它将有 2 个匹配 (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 正则表达式匹配并从中获取一些信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆