IAm*_*aja 7 regex string-matching dart
我正在尝试将我的Dart Web应用程序设置为:(1)确定特定字符串是否与给定的正则表达式匹配,以及(2)如果匹配,则从字符串中提取组/段.
具体来说,我想确保给定的字符串具有以下形式:
http://myapp.example.com/#<string-of-1-or-more-chars>[?param1=1¶m2=2]
Run Code Online (Sandbox Code Playgroud)
哪里<string-of-1-or-more-chars>就是:1+字符任何字符串,并在查询字符串([?param1=1¶m2=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.
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我知道我正在使用RegExp API错误(我甚至没有testURL在任何地方使用),最重要的是,我不知道如何使用RegExp API来提取(在这种情况下)" fizz"分段/分组的URL.
试试这个正则表达式:
String regex = "^http://myapp.example.com/#([^?]+)";
Run Code Online (Sandbox Code Playgroud)
然后抓取: matches.group(1)
RegExp 类带有用于单个匹配的便捷方法:
RegExp regExp = new RegExp(r"^http://myapp.example.com/#([^?]+)");
var match = regExp.firstMatch("http://myapp.example.com/#fizz?a=1");
print(match[1]);
Run Code Online (Sandbox Code Playgroud)
注意:我使用了 anubhava 的正则表达式(你的没有正确地转义 ?)。
注意2:即使这里没有必要,对正则表达式使用原始字符串通常是个好主意,因为您不需要在其中转义 $ 和 \ 。有时使用三引号原始字符串也很方便:new RegExp(r"""some'weird"regexp\$""").
| 归档时间: |
|
| 查看次数: |
6525 次 |
| 最近记录: |