【发布时间】:2026-01-16 02:05:01
【问题描述】:
我正在尝试让我的 Dart Web 应用程序:(1) 确定特定字符串是否与给定的正则表达式匹配,以及 (2) 如果匹配,则从字符串中提取一个组/段。
具体来说,我想确保给定的字符串具有以下形式:
http://myapp.example.com/#<string-of-1-or-more-chars>[?param1=1¶m2=2]
<string-of-1-or-more-chars> 就是这样:任何 1+ 个字符的字符串,并且查询字符串 ([?param1=1&param2=2]) 是可选。
所以:
- 判断字符串是否匹配正则表达式;如果是的话
- 从字符串中提取
<string-of-1-or-more-chars>组/段
这是我最好的尝试:
String testURL = "http://myapp.example.com/#fizz?a=1";
String regex = "^http://myapp.example.com/#.+(\?)+\$";
RegExp regexp= new RegExp(regex);
Iterable<Match> matches = 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 来提取 (在这种情况下)URL 中的“fizz”段/组。
【问题讨论】:
标签: regex dart string-matching