我正在尝试将我的Dart Web应用程序设置为:(1)确定特定字符串是否与给定的正则表达式匹配,以及(2)如果匹配,则从字符串中提取组/段.
具体来说,我想确保给定的字符串具有以下形式:
http://myapp.example.com/#[?param1=1¶m2=2]
哪里
就是:1+字符任何字符串,并在查询字符串([?param1=1¶m2=2]
)是可选的.
所以:
确定字符串是否与正则表达式匹配; 如果是这样
从字符串中提取组/段
这是我最好的尝试:
String testURL = "http://myapp.example.com/#fizz?a=1"; String regex = "^http://myapp.example.com/#.+(\?)+\$"; RegExp regexp= new RegExp(regex); Iterablematches = regexp.allMatches(regex); String viewName = null; if(matches.length == 0) { // testURL didn't match regex; throw error. } else { // It matched, now extract "fizz" from testURL... viewName = ??? // (ex: matches.group(2)), etc. }
在上面的代码中,我知道我正在使用RegExp API错误(我甚至没有testURL
在任何地方使用),最重要的是,我不知道如何使用RegExp API来提取(在这种情况下)" fizz"分段/分组的URL.
试试这个正则表达式:
String regex = "^http://myapp.example.com/#([^?]+)";
然后抓取: matches.group(1)